这是一个项目,包括从应用程序注册用户并在MySQL数据库中注册。这适用于Swift 2.3,但我想在Swift 3中实现它,我不知道如何解决它。
URLSESSIONS.shared.dataTask上的错误
代码:
else{
let url = URL(string: "http://localhost/billpain/secure/register.php")!
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
let body = "username=\(usernameTxt.text!.lowercased())&password=\(passwordTxt.text!)&email=\(emailTxt.text!)&fullname=\(firstnameTxt.text!)%20\(lastnameTxt.text!)"
request.httpBody = body.data(using: String.Encoding.utf8)
**URLSession.shared.dataTask(with: request, completionHandler: {(data:Data?, response:URLResponse?, error:NSError?) in**
if error == nil {
DispatchQueue.main.async(execute: {
do {
let json = try JSONSerialization.jsonObject(with: 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("Caught an error: \(error)")
}
})
} else{
print("error: \(error)")
}
}).resume()
答案 0 :(得分:0)
let url = URL(string: "http://localhost/billpain/secure/register.php")!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let body = "username=\(usernameTxt.text!.lowercased())&password=\(passwordTxt.text!)&email=\(emailTxt.text!)&fullname=\(firstnameTxt.text!)%20\(lastnameTxt.text!)"
urlRequest.httpBody = body.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
print("error:", error)
return
}
do {
guard let data = data else { return }
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
else { return }
print("json:", json)
} catch {
print("error:", error)
}
}task.resume()