与session.dataTaskWithRequest UIAlertView问题

我有这个代码来validationIAP收据,我试图显示一个基于这个函数返回的状态的警报,但我不断收到这个错误

"This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release. ....... ( then a whole list of numbers and stuff)" 

这是我使用的代码,(很简单)。 我猜它与线程和asynchronous的东西有关,我不太确定。 我如何以正确的方式做到这一点?

  func verifyPaymentReceipt(transaction: SKPaymentTransaction, completion : (status : Bool) -> ()) { .... //Verify Receipt code let task = session.dataTaskWithRequest(storeRequest, completionHandler: { data, response, error in if(error != nil){ //Handle Error } else{ completion(status: true) } } 

这就是我所说的function:

 verifyPaymentReceipt(transaction, completion: { (status) -> () in if status { print("Success") self.showMessage(true) } else { print("Fail") self.showMessage(false) } }) 

这是显示信息function

  func showMessage(message: Bool) { var alert = UIAlertView() if message == true { alert = UIAlertView(title: "Thank You", message: "Your purchase(s) are succeessful", delegate: nil, cancelButtonTitle: "Ok") } else { alert = UIAlertView(title: "Thank You", message: "Your purchase(s) restore failed, Please try again.", delegate: nil, cancelButtonTitle: "Ok") } alert.show() } 

只需修改showMessage()例程即可跳回主线程:

 func showMessage(message: Bool) { dispatch_async(dispatch_get_main_queue(), { () -> Void in var alert = UIAlertView() if message == true { alert = UIAlertView(title: "Thank You", message: "Your purchase(s) are succeessful", delegate: nil, cancelButtonTitle: "Ok") } else { alert = UIAlertView(title: "Thank You", message: "Your purchase(s) restore failed, Please try again.", delegate: nil, cancelButtonTitle: "Ok") } alert.show() }) } 

尽pipe您可能也想要更新以使用UIAlertController而不是已弃用的UIAlertView 。 除非你仍然需要支持iOS 7。

或者你可以把这行代码放到verifyPaymentReceipt() ,这样你从那里做的任何事情都会回到主线程。 两者都是可以接受