2016-01-18 58 views
0

我很難理解完成處理程序。我試圖讓一個函數(purchaseRequest)等待,直到另一個函數(didReceiveResponse)不被我調用,而是作爲委託完成。有人能給我一個關於如何實現這一目標的指針嗎?在委託方法中添加完成處理程序

func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) { 
    print("response received") 
    if response.products.count != 0 { 
     productsArray = response.products[0] 
     print(productsArray) 
    } else { print("No Products Found") } 
} 

func purchaseRequest() { 
    requestProductInfo() 

    //NEED TO HOLD UNTIL didReceiveResponse (which, as a delegate method, is not called by me) IS DONE. 
     print("Product1: \(self.productsArray)") 
    let aSC = UIAlertController(title: "Premium App Required", message: "Premium App is Required for this feature. Would you like to purchase it for $0.99?", preferredStyle: UIAlertControllerStyle.ActionSheet) 
    let buyAction = UIAlertAction(title: "Purchase", style: UIAlertActionStyle.Default) { (action) -> Void in 
     let payment = SKPayment(product: self.productsArray) 
     SKPaymentQueue.defaultQueue().addPayment(payment) 

    } 
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (action) -> Void in 
    } 
    aSC.addAction(buyAction) 
    aSC.addAction(cancelAction) 
    self.presentViewController(aSC, animated: true, completion: nil) 
} 

回答

1

•推進度微調視圖控制器

•使purchaseRequest後立即返回requestProductInfo()

requestProductInfo()後的委託方法捕獲代碼的新方法

•,dispatch_async()到主隊列並調用新方法

•在新方法中,彈出微調視圖控制器,然後進行高級購買舞蹈

+1

謝謝!我所做的是調用requestProductInfo(),然後使用dispatch_async()在didReceiveResponse委託內部進行purchaseRequest! –

+0

@JacoboKoenig太棒了!小心「一路阻擋」陷阱;回調處理程序調用異步方法傳遞迴調處理程序,該回調處理程序使用回調處理程序調用另一個方法。 (我充滿罪責)。在某個時候,您想要將回調處理程序重構爲自己的方法,然後調用它。 – bbum

相關問題