1
私のPHPサーバーからjSON応答を取得した後にUIAlertControllerを表示したいので、応答の戻りID、if else文、私はUIAlertControllerを表示するコードを書いたが、私はそれを動作させることができませんでした。 [UIKeyboardTaskQueue waitUntilAllTasksAreFinished]UIAlertControllerが表示されず、エラーが発生する(Swift、Xcode)
マイ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