2016-07-30 17 views
1

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

答えて

1

あなたが作業している警告コントローラーを表示しようとしている - ここで

はで私のエラー

アサーション失敗の抜粋です別のスレッド上に表示されるので、表示する前に元に戻す必要があります。

+0

ありがとうございます! – LuidonVon

+0

それから、upvotingと正解としてマークすることを検討してください – Moriya

関連する問題