2016-07-30 2 views
1

PHP 서버에서 jSON 응답을받은 후 UIAlertController를 표시하고 싶습니다. 따라서 응답에서 리턴 ID가있는 경우 if else 문에서 확인하십시오. , 나는 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() 
} 

답변

1

당신은 당신이 작업하고있는 경고 컨트롤러를 표시하기 위해 노력하고있다 별도의 스레드에 있으므로 표시하기 전에 다시 전환해야합니다.

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

감사합니다. – LuidonVon

+0

다음 upvoting 고려하고 정답으로 표시하십시오 – Moriya

관련 문제