ios - UIAlertView 问题与 session.dataTaskWithRequest

标签 ios swift sprite-kit

我有这段验证 IAP 收据的代码,我试图根据此函数返回的状态显示警报,但我一直收到此错误

"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)"

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

 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)
    }

}

这就是我调用该函数的方式:

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

这就是显示消息功能

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

尽管您可能还想更新为使用 UIAlertController 而不是 UIAlertView,后者已被弃用。除非您仍然需要支持 iOS 7。

或者您可以将此行放入 verifyPaymentReceipt() 中,这样您从那里所做的任何事情都会返回到主线程。两者都是可以接受的选择。

关于ios - UIAlertView 问题与 session.dataTaskWithRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35473635/

相关文章:

swift - Swift Bugging 中的 anchor ?

ios - 移动物理体 - didSimulatePhysics 与更新

ios - CFBundleGetFunctionPointerForName 和 dlsym 对于导出函数返回 NULL

android - 如何在 React Native 中访问嵌套的 Text 元素中的链接?

ios - 如何在后台使用地理围栏方法

ios - 使用 Swift 在 TableView 中的自定义单元格下添加图例

swift - 使用 Swift 从不同的类访问 SKCameraNode

iOS WKWebview : Always allow camera permission

ios - 编辑期间阻塞的字段。 ( swift - iOS)

ios - 将数组中的项目从最近到最公平排序(从我的位置开始)