0

I might be doing something wrong, but I can't seem to make my function wait for the data to load before it continues with the next sections. In this case, I need requestProductInfo() to supply the data before the alert in the next step to show. From what I have read, dispatch_async would be the correct way to do it, but it does not seem to be working. Am I doing something wrong?

func purchaseRequest() {
    requestProductInfo()
    //NEED TO HOLD UNTIL PRODUCTS REQUEST IS COMPLETED
    dispatch_async(dispatch_get_main_queue()) {
        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)
    }
}

Thanks!

Lyndsey Scott
  • 37,080
  • 10
  • 92
  • 128
Jacobo Koenig
  • 11,728
  • 9
  • 40
  • 75
  • You should use a block returning the result of `requestProductInfo()`, so when the block gives you a result then you can execute the rest of the code. – Pablo A. Jan 18 '16 at 16:34
  • 1
    You'll need to show more detail about the `requestProductInfo()` function. `dispatch_async` as you have it is to ensure the enclosed code operates on the main queue. It executes immediately after the call to `requestProductInfo`. Best solution would be to add a completion block to the function that is called when the request is completed. You could also use an `NSNotification`, but a completion block is a better implementation. – shim Jan 18 '16 at 16:34
  • Thank you Both. Could you please provide an example of using the completion block if its not too much trouble? I am new in the subject. Please do it in the main answer section so I can approve the answer and upvote you. – Jacobo Koenig Jan 18 '16 at 16:43
  • http://stackoverflow.com/questions/24231680/loading-image-from-url/27712427#27712427 completion sample – Leo Dabus Jan 18 '16 at 17:11

0 Answers0