在委托方法上添加完成处理程序

时间:2016-01-18 19:07:48

标签: ios swift completionhandler

我很难理解完成处理程序。我试图让一个函数(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 个答案:

答案 0 :(得分:1)

•推进进度微调器视图控制器

purchaseRequest

后立即返回requestProductInfo()

•在新方法中requestProductInfo()之后捕获代码

•在委托方法中,dispatch_async()到主队列并调用新方法

•在新方法中,弹出微调器视图控制器,然后进行高级购买舞蹈