Handling StoreKit Errors

The error state is one of the five UI states. It is pretty important in regards to the user’s experience and satisfaction. If you don’t handle errors probably, they can quickly become the main reason why users lose control of the app, and as a consequence, lead to a reduction in retention or even deletion of the app. 

Error handling is more important when you work with dependencies, especially when working with a library like StoreKit. In general, StoreKit is a black-box in which anything can happen. In this short article, we will explore how to handle failed transactions and give feedback to the user with appropriate error messages.

Alert to display when SKError Domain 0 occurs

NSError Overview

I’d like to start by giving a quick reminder of how NSError works, as we will be working with it in this article. Any error that happens on iOS includes the error domain, a domain-specific error code, and additional information specific to the application. So, for us the most important fields are:

Variety of SKErrors

Errors associated with payments, store products, and cloud services occur under the domain model SKErrorDomain and error codes SKError.Code. The entire list of errors includes more than 15 options, you can find them here below and in the documentation. In addition to SKErrorDomain errors, there may be network problems that occur in the NSURLErrorDomain model. Let’s take a look at how to handle them all.

There are a lot of types of errors, so I‘d recommend dividing them into several groups:

  • external, which cannot be influenced in any way, for example, network problems
  • request errors such as incorrect product ID
  • user side errors such as canceling an operation or an unverified account

Handling StoreKit errors

For error handling, we need to implement two methods of the SKRequestDelegate delegate.

optional func request(_ request: SKRequest, didFailWithError error: Error)

This is an optional method that receives errors from SKRequest. It is important to keep in mind that when these errors occur, (void) requestDidFinish: (SKRequest *) request will not be called.

The second point of failure is transaction processing, here errors are quite varied and can be associated with both when the user canceled the operation, and when rights have been restricted, such as parental controls. In order to be able to receive errors when working with transactions, it is necessary to process the the transaction status SKPaymentTransactionStateFailed separately. To get these events you should have a skpaymenttransactionobserver.

- (void)paymentQueue:(nonnull SKPaymentQueue *)queue
 updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
  for (SKPaymentTransaction *transaction in transactions) {
	  switch (transaction.transactionState) {
	    case SKPaymentTransactionStatePurchasing:
	      break;
	    case SKPaymentTransactionStatePurchased:
	      // implement handling purchased state
	      // [self handlePurchasedTransaction:transaction];
	      break;
	    case SKPaymentTransactionStateFailed:
	      [self handleFailedTransaction:transaction];
	      break;
	    case SKPaymentTransactionStateRestored:
	      // implement handling restored state
	      // [self handlePurchasedTransaction:transaction];
	      break;
	    default:
	      break;
	  }
  }
}

You should handle paymentQueue(_:updatedTransactions:) and all states of these transactions.

However, in this article we will dive deep into .failed states. As Apple mentions in their official documentation, you should get the error field from this transaction and then check the list of SKErrorDomain errors

func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .failed:
handleFailedTransaction(transaction)
case ...
}
}
}

How to handle SKErrors:

func handleFailedTransaction(_ transaction: SKPaymentTransaction) {
guard let error = transaction.error as? SKError else { return }

switch error.code {
case ...:
}
}


Let’s take a look at all the possible cases of StoreKit errors.

.unknownSKErrorUnknown code 0

This error SKErrordomain 0 return usually happens when an unknown or unexpected error has occurred. Usually, there is no need to take any action on the developers side, but here are a few recommendations to check: 

  1. Check the LocalizedDescription property of the error object.
  2. If the error appeared during the testing, try logging out or try it with a new test user. 
  3. The problem might be on the user’s account side, so it is worth asking the users to check and see if anyone gets back to you with more information.

.SKErrorClientInvalid code 1

This error is displayed when someone without the required permissions tries to perform the action. No action is needed to be done on your side. However, it is possible to try and show an automated notification with a message related to the action such as: “due to …. you are not allowed to perform the action. Please, change your account or device”.

.SKErrorPaymentCancelled code 2

This error code indicates that the user canceled a payment request. No action is needed from your side, however, you could try to look at the user’s behavior to find the right trigger to encourage the user to complete the payment in the future – such as an offer or triggered email that talks about the value of your app. The best reaction to this error would be to catch the event and send the user an automated notification with a discount offer or something else of value to try and encourage them to continue using your app.

.SKErrorPaymentInvalid code 3

This error shows that the payment was not processed correctly due to an issue with the billing – Error code indicating that one of the payment parameters wasn’t recognized by the App Store, card expiration or not enough funds. Try to check whether the billing issue is related to card expiration and if so, the best idea is to catch this error, and send an automated notification or email with a reminder to your user. 

.SKErrorPaymentNotAllowed code 4

An error code that indicates that the user is not allowed to authorize payments.

.SKErrorStoreProductNotAvailable code 5

This error might happen when your user tries to purchase a product that is unavailable in their region. Check SKStorefront.

.SKErrorCloudServicePermissionDenied code 6

Error code that indicates that the user has not allowed access to Cloud service information.

.SKErrorCloudServiceNetworkConnectionFailed code 7

This error occurs when the user tries to complete an action without a proper internet connection. Your best bet is to show them a notification highlighting that their connection is unstable, such as “please make sure that you have a proper internet connection, and try again later”.

.SKErrorCloudServiceRevoked code 8

Error code indicating that the user has revoked permission to use this cloud service.

.SKErrorPrivacyAcknowledgementRequired code 9

Error code indicating that the user has not yet accepted Apple’s privacy policy for Apple Music.

.SKErrorUnauthorizedRequestData code 10

Error code indicating that the app is attempting to access a property for which it does not have the required permissions.

.SKErrorInvalidOfferIdentifier code 11

This error indicates that the specified subscription offer identifier is not valid. For instance, you have not set up an offer with that identifier in the App Store, or you have revoked the offer. The best way to do this is to show the user a screen with your support team’s contact details.

.SKErrorInvalidSignature code 12

The cryptographic signature provided is not valid. This error indicates that the promo offer purchase has been created incorrectly. There is no reason to show this error to the user – it’s best to handle this error and fix this within your infrastructure.

.SKErrorMissingOfferParams code 13

One or more parameters from SKPaymentDiscount are missing. Same as above.

.SKErrorInvalidOfferPrice code 14

This error indicates that the price of the selected offer is not valid, for instance, the price with a discount applied is lower than  the current base subscription price.

NSURLErrorNotConnectedToInternet

A network resource was requested, but an internet connection has not been established and can’t be established automatically.

How to handle StoreKit errors?

There are a lot of types of errors, so I‘d recommend dividing them into several groups:

  • external, which cannot be influenced in any way, such as network problems
  • request errors such as an incorrect product ID
  • user side errors such as canceling an operation or an unverified account

External SKErrors

.For external errors, displaying an alert about the error itself is usually enough, as well as a repeat button so the user can try and complete the purchase again. This error can occur in moments such as when there is no internet or when there’s an error connecting to the App Store. Example: SKErrorUnknown code 0 (SKErrorDomain error 0).

Request SKErrors

This is a group of errors that can cause the greatest damage to positive conversations about the app, as they are system problems, for example, SKErrorStoreProductNotAvailable or SKErrorInvalidOfferPrice. Errors in this group must be covered by additional logging, as well as having the ability to catch them remotely on the server and fix them from there.

User side SKErrors

This group of errors is directly related to the user’s state, for example: SKErrorClientInvalid code 1, SKErrorPaymentCancelled code 2, SKErrorPrivacyAcknowledgementRequired code 9.

Correct error handling within the application is a very important part of the user experience. First of all, I would recommend implementing the error while still in the loading state and only after that, start implementing the main (content) state.