2016-02-18 35 views
0

我有這樣的代碼,用於驗證IAP收入和我試着基於什麼狀態此功能被返回來顯示一個警告,但我不斷收到此錯誤UIAlertView中的問題與session.dataTaskWithRequest

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

} 

回答

1

只需修改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(),以便你從那裏做的任何事情都能回到主線程。兩者都是可接受的選擇

+0

是的我知道'UIAlertView'已被棄用。 (很難不知道什麼時候這個黃色的感嘆號不斷提醒你),但無論如何感謝!哪裏是添加它的理想場所?在'verifyPaymentReceipt()'函數調用之後,還是應該在'task'之後? –

+0

這取決於哪個塊在後臺線程中運行。您可以通過添加一個斷點並在您點擊它時在左側的調試導航列表中查看線程號來查找。 –

+0

謝謝!我正在學習編程,這是我的第一個應用程序。像你這樣的人給了我很多需要的指導,我真的很感激。謝謝!! –