UIAlertController无法显示并不断出错(Swift,Xcode)

时间:2016-07-30 07:56:01

标签: php swift xcode

我想从我的php服务器获取jSON响应后显示一个UIAlertController,所以在检查响应中有一个返回id时,在if else语句中,我写了一个代码来显示一个UIAlertController但是我不能让它发挥作用。

以下是我的错误摘录

断言失败 - [UIKeyboardTaskQueue waitUntilAllTask​​sAreFinished]

我的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()
}

1 个答案:

答案 0 :(得分:1)

当您尝试显示警报控制器时,您正在使用单独的线程,因此您需要在显示之前切换回来。

if(id.isEqual("")){
      NSOperationQueue.mainQueue().addOperationWithBlock {
          self.presentViewController(failAlert, animated: true){}
      }
}...