1
我想在从我的php服务器获得一个json响应后显示一个UIAlertController,因此在检查时,在if else语句中有一个来自响应的返回id ,我写了一个代码来显示一个UIAlertController,但我无法让它工作。UIAlertController无法显示并且一直出现错误(Swift,Xcode)
这里是我的错误
断言失败中的一个片段 - [UIKeyboardTaskQueue waitUntilAllTasksAreFinished]
我IBAction为按钮代码
@IBAction func btnRegister(sender: AnyObject) {
let parameters = ["name": tfName.text! , "contact": tfContact.text! ,"email": tfEmail.text!] as Dictionary<String, String>
let request = NSMutableURLRequest(URL: NSURL(string:"http://192.168.1.8/safeproject/registerprofile.php")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
let successAlert = UIAlertController(title: "Registration Status", message:"Register Success", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
let failAlert = UIAlertController(title: "Registration Status", message:"Register Fail", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
// Present the controller
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("Response: \(json)")
let id = json["id"]!
if(id.isEqual(""))
{
self.presentViewController(failAlert, animated: true){}
print("User register fail");
}
else
{
self.presentViewController(successAlert, animated: true){}
print("User register success");
}
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
}
谢谢你的工作! – LuidonVon
然后请考虑upvoting并将其标记为正确答案 – Moriya