StoreKit SKProductsRequest Crash

心已入冬 提交于 2019-11-28 00:42:37

A very likely explanation is whether the object you set as a delegate for the SKProductRequest object might have been deallocated already.

It is quite possible for the request to take a few seconds to complete, and this might be past the lifetime of your delegate object, so you may want to make sure it sticks around for long enough.

The answer above is technically correct but it is not complete. As Megastep said "the object you set as the delegate for the SKProductsRequest may have already been deallocated." Therefore you are sending a message to an object that has already been deallocated. Now onto the actual answer:

- (void)requestProUpgradeProductData {
    NSSet *productIdentifiers = //Your Product IDs go here

    productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
    productsRequest.delegate = self;
    [productsRequest start];

    // we will release the request object in the delegate callback
}

#pragma mark -
#pragma mark SKProductRequest Delegate Methods

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse(SKProductsResponse *)response {
self.products = response.products;
//NSLog(@"%i",[products count]);
proUpgradeProduct = [products count] == 4 ? [[products objectAtIndex:0] retain] : nil;
if (proUpgradeProduct)
{
    //Do your stuff here...
}

for (NSString *invalidProductId in response.invalidProductIdentifiers)
{
    //NSLog(@"Invalid product id: %@" , invalidProductId);
}

// finally release the reqest we alloc/init’ed in requestProUpgradeProductData
[productsRequest release];

[[NSNotificationCenter defaultCenter] postNotificationName:kInAppPurchaseManagerProductsFetchedNotification object:self userInfo:nil];
}

So basically as you can see above you do not need to release productsRequest because it is already being released in the delegate callback method. Again you do not need to call productsRequest release or set it Nil in viewDidUnload/dealloc method because that could cause a crash if you dismiss the view before the callback method gets called.

I'm using an object like a delegate. So in the deinit method of this object i remove the delegate a and crash has been fixed.

private var currentProductRequest: SKProductsRequest?

deinit {
    if let r = currentProductRequest {
        r.delegate = nil
        r.cancel()
        currentProductRequest = nil
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!