无法转换类型'的值(NSData?,URLResponse?,NSError?) - > ()'to expected argument type'(Data?,URLResponse?

时间:2018-03-27 12:41:28

标签: php mysql swift4

大家好我正在尝试使用Swift,我正在尝试发布用户注册数据。我知道怎么做firebase但我的主要项目是在php mysql所以我想用swift连接它

@IBAction func signUp(_ sender: Any) {

        //check textfield data
        checkTextFields()

        //create user
        let url = NSURL(string: "http://localhost:8888/helo/register.php")
        let request = NSMutableURLRequest(url: url! as URL)
        request.httpMethod = "POST"

        //apending body to url
        let body = "Fullname=\(name.text!.lowercased())&userName=\(userName.text!.lowercased())&emailAddress=\(emailAddress.text!.lowercased())&password=\(password.text!.lowercased())"
        request.httpBody = body.data(using: String.Encoding.utf8)


        //lunching
        URLSession.shared.dataTaskWithRequest(request as URLRequest, completionHandler: { (data:NSData?, response:URLResponse?, error:NSError?) in

            if error == nil{

                dispatch_async(dispatch_get_main_queue(),{
                    do {
                        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as?
                        NSDictionary

                        guard let parseJSON = json else{
                            print("Error while parsing")
                            return
                        }
                        let id =  parseJSON["id"]

                        if id != nil {
                            print(parseJSON)
                        }

                    }catch{
                        print("Caugth an error: \(error)")
                    }

                })
            }else{
                print("error: \(error)")
            }
        } )
    }

我收到的错误就是我所评论的行,就像说午餐一样

Cannot convert value of type '(NSData?, URLResponse?, NSError?) -> ()' to expected argument type '(Data?, URLResponse?, Error?) -> Void'

我是Swift的新手,欢迎任何帮助,谢谢大家。我正在使用Xcode 9

1 个答案:

答案 0 :(得分:0)

经过充分阅读后,我才意识到,当事情有所改善时,我正在做一个非常繁琐且使用正统方法的方法。我删除了整个代码并使用Alamofire完成了所有操作。它非常简单直接。我将发布以下代码,以帮助后来遇到类似问题的其他人。

//Constant that holds the URL for our web servicer
        let URL_USER_REGISTER = "http://localhost:8888/members/register.php?"

        Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON{
                response in
                //printing response
                print(response)

                //getting json value from the server
                if let result = response.result.value {

                    //converting it as NSDictionary
                    let jsonData = result as! NSDictionary

                    //displaying the message in label
                    self.lableMessage.text = jsonData.value(forKey: "message") as! String?
                }
        }

你必须先导入Alamofire。