Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
In-App Purchases (Obj-C)
// Called in viewDidLoad callback.
- (void)validateProducts
{
NSString *productId = @"product_id_from_app_store_connect";
NSSet *productIdentifiers = [NSSet setWithObject:productId];
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
request.delegate = self;
self.productsRequest = request;
[self.productsRequest start];
}
// Called when user taps "Subscribe" or "Purchase" or whatever.
- (void)subscribeUser
{
if (![SKPaymentQueue canMakePayments]) {
[self displayErrorWithTitle:@"Oops" message:@"You aren't allowed to make in-app purchases. Please update your Settings and try again"];
return;
}
if (!self.subscriptionProduct) {
DDLogError(@"no subscription to purchase");
[self displayErrorWithTitle:@"We're Sorry" message:@"Something went wrong. Please try again."];
return;
}
SKPayment *payment = [SKPayment paymentWithProduct:self.subscriptionProduct];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
// Called when user taps a "restore my purchase" button.
- (void)restoreSubscription
{
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
#pragma mark - <SKPaymentTransactionObserver>
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions
{
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased:
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
// Any other custom success handling logic, e.g. pop-up.
break;
case SKPaymentTransactionStateRestored:
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
// Restoration logic, pop-up, etc.
break;
case SKPaymentTransactionStateFailed:
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
// Show error, etc.
break;
default:
// Probably shouldn't happen, might want to display an error.
break;
}
}
}
#pragma mark - <SKProductsRequestDelegate>
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
// Below assumes one possible product for purchase, modify if you support multiple.
if (response.products.count != 1) {
DDLogError(@"Subscription product not valid");
}
else {
self.subscriptionProduct = response.products[0];
}
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
// Any custom logic to display the available products or buttons to purchase.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.