使用http请求

时间:2016-10-17 18:54:48

标签: swift nsurlconnection

尝试将在文本字段中输入的变量发送到php脚本以写入sql数据库。尝试使用HTTP请求

@IBAction func submit(_ sender: AnyObject) {

    let requestURL = NSURL(string: "***************")

    let request = NSMutableURLRequest(url: requestURL! as URL)

    request.httpMethod = "POST"

    let song=txt1.text!
    let artist=txt2.text!
    let album=txt3.text!
    let year=txt4.text!
    let genre=txt5.text!


    let songPost = "song=" + (song as String)
    let artistPost = "&artist=" + (artist as String)
    let albumPost = "&album=" + (album as String)
    let yearPost = "&year=" + (year as String)
    let genrePost = "&genre=" +  (genre as String)

    request.httpBody = songPost.data(using: String.Encoding.utf8);
    request.httpBody = artistPost.data(using: String.Encoding.utf8);
    request.httpBody = albumPost.data(using: String.Encoding.utf8);
    request.httpBody = yearPost.data(using: String.Encoding.utf8);
    request.httpBody = genrePost.data(using: String.Encoding.utf8);
    NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.mainQueue)

我在代码读取的底线出现错误:在调用中缺少参数'completion hander'的参数。

不确定这意味着什么。

2 个答案:

答案 0 :(得分:0)

这里的错误实际上非常清楚。此方法有一个名为completionHandler的第三个参数,您将丢失该参数。 Documentation。用这个替换你的最后一行:

NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.mainQueue)
{
  response, data, error in
  // handle response here
}

答案 1 :(得分:0)

正如我在评论中提到的,你不应再使用NSURLConnection了。但我回答你的问题,因为如果你将来遇到类似的错误,它可能对你有帮助。

消息说,您正在调用参数少于所需参数的函数。在这种情况下,completionHandler缺失。

NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.mainQueue, completionHandler: {
     response , data, error in
})

在Swift 3中,你也可以像这样建立一个完成处理程序:

NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {
    response , data, error in
    // your code here
}

BTW:在Swift中,您不需要使用NSMutableURLRequest。使用URLRequest已将var变为可变。