Skip to content

Instantly share code, notes, and snippets.

@bswags
Created August 22, 2019 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bswags/638621b628987122eeb85e81d1b367f3 to your computer and use it in GitHub Desktop.
Save bswags/638621b628987122eeb85e81d1b367f3 to your computer and use it in GitHub Desktop.
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