Php UIAlertController无法显示,并不断出现错误(Swift、Xcode)

Php UIAlertController无法显示,并不断出现错误(Swift、Xcode),php,swift,xcode,Php,Swift,Xcode,我想在从我的php服务器获得jSON响应后显示UIAlertController,因此在检查响应是否有返回id后,在if-else语句中,我编写了一个代码来显示UIAlertController,但我无法让它工作 下面是我的一个错误片段 -[UIKeyboardTaskQueue WaitUntillallTasksRefiefined]中的断言失败 我的IBAction按钮代码 @IBAction func btnRegister(sender: AnyObject) { let

我想在从我的php服务器获得jSON响应后显示UIAlertController,因此在检查响应是否有返回id后,在if-else语句中,我编写了一个代码来显示UIAlertController,但我无法让它工作

下面是我的一个错误片段

-[UIKeyboardTaskQueue WaitUntillallTasksRefiefined]中的断言失败

我的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()
}
@IBAction func btnRegister(发送方:AnyObject){
让参数=[“name”:tfName.text!,“contact”:tfContact.text!,“email”:tfEmail.text!]作为字典
let request=NSMutableURLRequest(URL:NSURL(字符串:)http://192.168.1.8/safeproject/registerprofile.php")!)
let session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
//注意:添加相应的“contenttype”和“Accept”头。
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
request.HTTPBody=try!NSJSONSerialization.dataWithJSONObject(参数、选项:[])
让task=session.dataTaskWithRequest(请求){数据,响应,错误
防护数据!=无其他{
打印(“未找到数据:\(错误)”)
返回
}
让successAlert=UIAlertController(标题:“注册状态”,消息:“注册成功”,首选样式:。警报)
addAction(UIAlertAction(标题:“OK”,样式:。默认值){in})
让failAlert=UIAlertController(标题:“注册状态”,消息:“注册失败”,首选样式:。警报)
addAction(UIAlertAction(标题:“OK”,样式:。默认值){in})
//呈现控制器
做{
如果让json=尝试NSJSONSerialization.JSONObjectWithData(data!,选项:[])作为NSDictionary{
打印(“响应:\(json)”)
让id=json[“id”]!
如果(id.isEqual(“”)
{
self.presentViewController(failAlert,动画:true){}
打印(“用户注册失败”);
}
其他的
{
self.presentViewController(successAlert,动画:true){}
打印(“用户注册成功”);
}
}否则{
让jsonStr=NSString(data:data!,encoding:NSUTF8StringEncoding)//不抛出错误,但不抛出NSDictionary
打印(“错误无法解析JSON:\(jsonStr)”)
}
}捕获let解析错误{
print(parseError)//记录`JSONObjectWithData'引发的错误`
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法分析JSON:'\(jsonStr)'”)
}
}
task.resume()
}

当您试图显示警报控制器时,您正在一个单独的线程上工作,因此需要在显示之前切换回

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

请考虑投票并将其标记为正确答案。