nico_dindon
nico_dindon

Reputation: 21

SKProductsRequest won't call my callback in Swift 2

I follow different tutorials to retrieve products informations in a iOS app in Swift 2. But I can't make it works :-/

I make the following code as simple a possible, I just call the requestProductsSimple method, and I'm expecting productRequest() to be call. I have 0 error and 0 warning before running.

But output only show:

request started

ended

And I got a EXEC_BAD_ACCESS after few seconds. Here is the code. I wish someone can help.

Thanks :)

import UIKit
import StoreKit

class ViewController: UIViewController {

    @IBOutlet var mainView : UIView?

    override func loadView() {
        super.loadView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let shop = IAPHelper()
        shop.requestProductsSimple()

        print("ended")

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}


class IAPHelper: NSObject, SKProductsRequestDelegate {

    override init() {

    }

    func requestProductsSimple() {

        let productIdentifiers: Set<String> = ["my_product_id"]
        let productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
        productsRequest.delegate = self
        productsRequest.start()

        print("request started")

    }

    func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {

        print("received")

    }

    func request(request: SKRequest, didFailWithError error: NSError) {

        print("request failed")

    }

}

Upvotes: 1

Views: 391

Answers (1)

Paulw11
Paulw11

Reputation: 115076

Since your shop is a local variable, it will be released once viewDidLoad returns. This is before the asynchronous operation has completed and you then get a segmentation fault when it tries to call the now released completion method.

Move your shop to a property so that a strong reference is held after viewDidLoad returns

Upvotes: 1

Related Questions