Jacobo Koenig
Jacobo Koenig

Reputation: 12514

Adding a completion handler on a delegate method

I am having a hard time understanding completion handlers. I am trying to have a function (purchaseRequest) wait until another function (didReceiveResponse) which is not called by me, but as a delegate, is done. Can somebody give me a pointer on how to accomplish this?

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

Upvotes: 1

Views: 1183

Answers (1)

bbum
bbum

Reputation: 162712

• push a progress spinner view controller

• make purchaseRequest return immediately after requestProductInfo()

• capture the code after requestProductInfo() in a new method

• in the delegate method, dispatch_async() to the main queue and call the new method

• in the new method, pop the spinner view controller and then do your premium purchase dance

Upvotes: 2

Related Questions