2011 • 48:05
With In App Purchase and Notifications, you can add considerable value and functionality to your iOS apps. Learn how to create notifications for optimal performance, consistency, and user experience, and the entire purchase life cycle for in app payments.
Speaker: Nitin Mishra
Unlisted on Apple Developer site
Transcript
This transcript was generated using Whisper, it has known transcription errors. We are working on an improved version.
Hi, I'm Nitin Mishrha from Apple's Worldwide Developer Relations team. In this video, you'll learn about two great technologies you can implement to add value and functionality to your iOS applications. This session is designed to teach you about the architecture and implementation steps for adding notifications and in app purchases to your apps.
You'll find this video divided into two halves, with the first half focusing on push and local notifications and the second half diving into in app purchases. All throughout, we'll highlight the critical steps for feature implementation, as well as cover best practices and some common gotchas to help simplify your implementation experience with these two exciting features.
Let's start the day discussing notifications, which can include both push notifications or local notifications. Both of these are ways for an application that isn't running in the foreground to let its users know that it has something for them. At its core, notifications are simply a virtual tap on the shoulder, telling your users that your application has some piece of data waiting for them.
That tap could be a message, an impending calendar event, or some new data on a remote server. Notifications allow applications that operate in a time-sensitive environment, where events of interest to users can occur at any time, to notify those users when these events occur, even if the app isn't running.
To get a good idea of what notifications can be used for, let's take a look at some of the apps on the store that are really leveraging notifications in a great way. Notifications can be used in many different ways, and one of those most common uses for Push is to deliver breaking events to users. This can be news, sports scores, activities in your area, or anything of that nature. Here we see how ESPN is using Push notifications to keep users aware of a sporting event, and by acting on that notification, users are taken right into the game they're following.
Another use of notifications is to keep users aware of events that might be happening, such as game moves, instant messages, or social networking site updates. In this example, the ng-moco team has used push notifications to let the user know that they have a pending move to make in a game they're playing with some friends online.
In our last example, we can see how notifications can be used to remind the user of an action they scheduled, even if they're not in that application. Here we see that the user is busy playing a game, but wanted to be reminded when their favorite online radio show was set to begin so they could record it. So as you can see, there are a number of scenarios in which notifications can be used to really add value to your customer's experience with your application. Let's take a look in more depth at what you can do to add notifications to your application.
To begin, let's take a look at the different features of notifications. The first feature is that you can specify which events are important to your app and one of three types of notifications you can associate with these events. You can specify either a badge, which is displayed on your application icon, an alert box, which can display a message string of your choosing, or lastly, a sound file.
When you're choosing your types of notifications, use badges for actionable information. This is really helpful for users and it's less disruptive than some of the other notification methods. When you want to use alerts, only send messages that are worth knowing. Don't send non-essential information or advertising. And lastly, when you're using sounds, you should really use a distinct and short sound to really get the user's attention and know which application is calling them.
The second feature of notifications is that they are delivered whether your app is running or not. So your application can be closed and the user can be doing anything else with the device or the device can be turned off and those notifications will still attempt to be delivered.
And lastly, along those lines, is that notifications are a great way of preserving battery life, especially when compared to the alternative of having your app continuously run in the background. With notifications, you get all that functionality of a background app without having to use any additional CPU cycles, so you're really saving your user's battery life.
When we discuss notifications, it's important to understand that there are two different notification methods your app can use. The first method is push notifications. Push notifications are events that are sent from a remote server to your application through the Apple Push Notification service. The content which you send in a push notification originates from this content server which is outside of your application. The other type of notification method is local notifications. Local notifications don't require any server infrastructure, as the events themselves originate from within the application.
Let's take a look at how these two notification methods are similar. You'll notice that both push notifications and local notifications look identical. Both can use any of the three notification types we discussed earlier. The second similarity between these two notification methods is that in both methods, iOS will act directly on behalf of your app, meaning your app doesn't need to be running for these notifications to be delivered.
There are some differences between the two notification methods as well. The biggest and primary difference between the two is that push notifications originate from a remote server, whereas local notifications are scheduled from within your app. Push notifications, therefore, require some sort of connectivity in order to receive them, and this can be either cellular or Wi-Fi connection. Local notifications, on the other hand, don't require any network connectivity, since they're going to be scheduled and fired from within the application itself.
And lastly, push notifications are single shot. Once they've been sent, that's the end of them. You'll have to send a new push notification if you want to repeat some sort of information. However, local notifications are repeatable and schedule, meaning they can be set up to fire at any time interval of your choosing.
Whatever type of notification method you choose to use, it's helpful to understand that in either scenario, there are three main steps to implementing notification technology. The first step is that you'll have to build your notification, meaning you need to understand the notification format and the contents you want to deliver. The second step is that you'll need to send your notification.
In the case of push notifications, this means you'll need to understand how to configure your notification server to communicate with the Apple push notification service. And in local notifications, you'll need to understand how iOS schedules and handles notifications. Lastly, for both methods, you'll need to understand how the device and your app will handle these notifications once they're received. We'll talk through each of these three steps for both types of notification methods. And to start with, let's go with push notifications.
Below you'll see the five steps that are required if you wish to implement push notifications into your application. Let's walk through these steps for setting up your development assets, creating your content provider, constructing the push notification package, delivering your notification through the Apple Push Notification Service, and lastly, handling the notification on your device. Let's start with development preparation. These are the prerequisite items you'll need to complete if you want your app to receive push notifications.
The first thing you'll want to do when getting started with push notifications is to go to the iOS Developer Program Portal. This is the same place where you obtain your iOS code signing certs and provisioning profiles and add your development devices. In the App ID section of the Program Portal, you'll want to enable the App ID for the application you wish to use push with. Remember that only App IDs that have a specific bundle identifier included can be used for push. Wildcard App IDs cannot be. Enabling your App ID for push ensures that your bundle ID is registered and that no other developers can send notifications to your application.
After enabling your app ID, you'll then create client SSL certificates for each of those app IDs. These certificates will contain your bundle identifier within them and can be used to send notifications only to that specific application. You'll create two different kinds of SSL certificates. The first is a development SSL cert, which allows you to connect to the sandbox push environment.
This is great and what you'll need for testing your application prior to posting it to the app store. The second cert will be the production SSL cert, and this will allow you to connect your remote notification servers to the production Apple Push notification service. Lastly, in the portal, after you've enabled your app ID and obtained your SSL certificates, you'll need to create and download a Push Notification Configured Provisioning Profile. This provisioning profile will have a special entitlement in it, allowing your application to receive notifications from the service.
So now that we have all the assets we need for building our app and connecting it to the push notification service, maybe we should take a step back and look at why we need to do all this. So in our last step, we obtained a push notification provisioning profile.
And we can see that it has one of two values, APS environment development or APS environment production. These are the special entitlements which will signify to the device which environment it will be receiving notifications from. By building your application with that, your device will be ready to receive notifications.
The second step is to take your SSL certificates and use them to establish a trusted connection between your server and the Apple Push Notification Service. The device has its own certificate, which you don't need to worry about, but it allows itself to have its own trusted connection as well. By using these two certificates, we now have a trusted connection between your server and the iOS device. This allows us to send the notification directly to it.
Now that we have all the assets we need for building our app and connecting to the push notification service, we'll need to set up our content provider. Your provider can run on any operating system that supports TCP/IP TLS connections. You'll install the appropriate SSL certificate on this server, and again, you'll want to make sure the certificate user ID matches your application's bundle ID.
Otherwise, your notifications won't be delivered properly. Finally, you'll want to make sure you have firewall ports 2195 and 2196 open. With poking holes in these ports, you'll be able to send your notifications to the push notification service, as well as receive feedback information from the notification service, which we'll discuss a bit later.
So we've obtained our assets and set up our content provider. Our next step in the implementation process is to actually construct the notification package, all the data you actually want to send to your users. Your notification package consists of two objects. The first is the device token, and the second is the message payload. Your payload has a maximum length of 256 bytes and should only contain non-sensitive and non-critical data. Together, these two pieces of information make up the notification package which you'll be sending through the service.
Let's take a look at each of these two pieces in more detail. The first is the device token. The device token uniquely identifies your device to the Apple Push Notification service, and it is generated by the service for each device. One thing it's important to remember is that this is different from the UDID you enter for your device into the program portal. The UDID is a fixed value, which doesn't change over the lifetime of your device. However, your device token for the Push service actually can change in different scenarios.
Some of those scenarios are that your app is restored to a new device, or the same device is erased and the app is reinstalled without restoring from iTunes. Therefore, it's important that you call the registration API at each application launch, and you send this to your server every time that your application launches. Therefore, you always have the latest device token for your user's device.
Lastly, don't store this token on the disk as it can change. And remember, the development device token you receive from the sandbox push service is different than the production device token. So this will help you in your debugging techniques. If you're encountering some errors, you may be using the wrong device token.
The last part of your notification package is the message payload itself. This is the part of the notification that contains the information you actually want to provide to the user. The payload format is strict JSON, or Java Object Notation, though you don't need to know any JavaScript to use it.
We've chosen this format because JSON is both human-readable and very compact versus an XML counterpart. It's great for Cocoa property lists such as NSDate, NSString, NSDictionary, and NSNumbers. By being compact, we're able to keep the payload overhead down, allowing you to have more room in your notification for the actual message you want to display.
Along with that, the message payload will have an APS dictionary reserved for your sound, badge, and alert keys. All three of these keys are optional, so you can choose any type you want to use. In this instance, we're using all three keys: the alert, the badge, and the sound notification types. And that'll look like this to the user. The last part of the payload is reserved for your application, and you can put anything in it, such as an identifier for your notification, as long as it follows the JSON format.
Now that we've built our notification package, we're ready to connect with the Apple Push Notification service and deliver it to the user. To do this, we're first going to open the connection between our content server and the Apple Push Notification Service environment we want to push through. Each environment has its own unique address that you'll connect to, with the development environment having this address and the production removing Sandbox from that.
It's important to remember that if you're doing ad hoc or enterprise distributions, you're actually connecting to the production environment. So if you have your development certs configured, they won't work with these ad hoc or enterprise in-house apps. It's important that you keep your connection open across all of your notifications, instead of opening and closing it between each notification you send. This is because the push notification service may see this opening and closing as a denial of service attack.
So as good practice, you should just open the connection once and keep it open as long as you can. It is important to know that the server can close the connection on error. And some of these errors include an invalid payload length or token length, or a device token and server mismatch. So let's talk a little more about keeping that connection open between your server and the Apple Push Notification Service. The Push Notification Service is designed for high throughput and performance.
And therefore it acts as a streaming protocol, meaning you won't get a response for every message you send. By using your cert, you'll establish that trusted connection with the service, and then you'll be able to send millions and millions of messages to your users. And because the notification service is designed for high throughput, you won't see a response. However, you may send an invalid token, which will sever the connection between your notification server and the service.
And any notifications you have remaining in the queue will be orphaned. The problem is, you may not know which notification caused that error. So how are we able to identify and make it easier for you to pick up where you left off and send those orphaned notifications? The answer is to use the enhanced binary interface.
The enhanced binary interface is the protocol that you'll use to send notifications to the service. For those of you who may have used the push notification service before, you'll remember the initial binary interface, which included your notification payload and length, your device token and length, as well as your command identifier. With the enhanced binary interface, we've now added the ability for you to add a unique identifier to your notification. And upon error, the Apple Push notification service will return this identifier to you.
Additionally, we've added the ability to add an expiration period for a notification. Therefore, you won't be sending information that may no longer be usable or valuable to your users. The last step you'll do to implement this enhanced binary interface is to update your command ID from 0 to 1.
The Apple Push Notification Service also comes with a Feedback Service, and this is populated when a user removes your app from their device. The goal for you is to avoid sending notifications to deleted apps, as the user won't receive them, and it will reduce throughput through the Notification Service. The Feedback Service consists of a queue of device tokens of users who have removed your app, and this will include the device token, the token length, and a Unix timestamp.
In order to access the feedback service, you should open the connection with the Apple Push Notification Service using the same certificates you use to send notifications. You'll read that information until the connection closes, and ideally you'll be doing this at least once a day. Each environment will have its own unique connection URI, so you can access the development and production environments and get the feedback for each of those. As soon as you've read the queue of devices, it will be flushed from this feedback service. And the next time you access it, you'll have only new data.
The last step in implementing push notification is to handle the notification on the device. When you're handling notifications, there are three different types of situations your user can be in. The first is that the application isn't running. The second is that the application is running in the foreground, or the application could be running in the background. In order to handle notifications, your application will have to do three things. The first is to register for notifications. Then the second is to pass the device token for the device to your server. And lastly, you'll need to display the notification to the user.
When you're registering for notifications, you'll do this at your application launch time. As we identified earlier, you can choose from any combination of the alert message, sound types, or badge icon. After you've defined the types of notifications you'll want to use, you'll tell iOS that you want to register a given app on a specific device with the push notification service using the UIKit API. To do this, you'll call UI Application Register for Remote Notification Types with those three types of notifications you want your app to receive. Remember that just because you register for a certain type of notification, it doesn't mean the user can't turn them off.
After registering, you'll implement the registration callback. The first is the UI application delegate did register for remote notifications with device token. This method may not get called if the network is available, so don't consider it an error right away. At this point, you'll get a token back for your device, and you'll have to choose a method for sending this token back to your content provider. That method is completely up to you.
The other callback you'll implement is the Registration Error Callback. This is the UI application delegate did fail to register for remote notifications. You'll get this callback if your provisioning profile is not configured with the proper APS environment entitlement. Or, you may be trying to run this in the simulator, as the iOS simulator does not support the ability to receive notifications.
Now that you've registered for notifications, you'll want to decide how your app will behave when it actually receives the notification. And the first scenario is that your application isn't running when the user receives it. In this case, you'll call the UI application launch delegate, "Did finish launching with the options." This is going to be called when the user taps on the action button, or when the user unlocks the home screen within a certain amount of seconds of receiving that notification.
When you're using this, you can use the launch options dictionary in order to set context so that whenever a user clicks on an action button, you can take them directly to a particular area of your application. The second situation is that the application is already running in the foreground. And in this case, you'll implement the UI application notification delegate did receive remote notification. In this case, we're not going to send a badge or an alert message to the app.
However, you can do some sort of subtle action in your application itself. Since we're not sending an alert or a badge, you'll want to use the user info dictionary to subtly notify the user of the event that has taken place. In this case, we're subtly notifying them of a change in the score since they're already in the application. The goal here is to avoid changing the user context. Since they're already in your application, you don't want to send them somewhere else. One quick aside on user experience. As with anything, you don't want to annoy your users.
Therefore, use your alerts sparingly. And if you're going to use sounds, keep them short but distinct. Ideally, you'll want to have a branded sound file so that the user will know what application is actually trying to send them a notification. And lastly, use badges when possible for actionable items. They are the least intrusive and the most informative of the notification methods. And as a point, you should always allow your users to customize the notifications they want to receive, especially if you have several different event types for which you're sending notifications for.
So now that we've talked about implementing push notification, let's move on to local notifications. And as we talked about earlier, the biggest difference here is that local notifications don't require any remote server. Therefore, your setup is literally three steps. Construct your notification, deliver the notification, and handle it on the device.
So let's move on to local notifications. And in our first step, let's construct the notification. Just like remote notifications, you can use local notifications to set badges for your event. After you've created an instance of UI local notification, you'll use UI applications application icon badge number property to set that badge value. This can be any positive integer you want.
Secondly, you can also send an alert message or an alert string to your user via local notification. And to do so, you'll want to set the alert body and alert action properties. In this scenario here, we have an alert body that says baseball game starting now. As you can see, there's a button on it, meaning we want there to be some action. So we set the alert action to yes, and we set it to go watch the game.
So in this local notification alert message, we've notified the user that the game has started, that if there's an action for them to click on it, and they can go right into the app itself. And lastly, you can use sounds as local notifications as well. And these can be one of two different types. The first is a custom sound contained within your app bundle. To do so, you'll use the sound name property.
Secondly, you can use the default notification sound. Either of these will work, and they'll provide your users with the sound notification. Now that we've constructed our notification, we'll want to deliver it. And when we deliver local notifications, we're actually scheduling them, meaning we're setting a time for them to go off. It's not based on a particular event. They're all time-based. So we can schedule and cancel local notifications using the UI Application Class Method Schedule Notification. The matching cancel call will allow you to get rid of these notifications as well.
Now that we've created the notification, we need to set what time we want it to go off. To set the time when your notification will appear, you'll use the Fire Date and Time Zone properties. When dealing with these properties, it's important to keep in mind the concept of time.
If you want to schedule a notification for one day from now, it's not necessarily 60 seconds times 60 minutes times 24 hours, as the user could change time zones. So, instead of using this time-based math to calculate when we want these events to go off, let's use NSDate components instead. This will ensure that your users are receiving these notifications at the appropriate time and not necessarily some calculated time.
Additionally, you can use the repeat interval and repeat calendar properties to schedule repeating notifications. Therefore, this can be set up so that local notifications can be delivered at any NS calendar unit component, such as every day, hour, or week. Now that we've decided the time we want the notification to be delivered, we'll need to handle the notification on the device. And just like with push notifications, we have our three different scenarios.
The application cannot be running, it can be running in the foreground, or it can be one of the special apps that are running in the background. When the application is not running, we're going to handle the notifications just like a push notification, meaning we'll use UI applications did finish launching with options. And again, we'll have our launch options, and our only difference here will be the launch options local notification key.
When the application is running in the foreground, iOS is not going to set any alerts or badges. Therefore, it's up to you to use the User Info Dictionary to set the context for the user so that they can subtly be notified of the event. And lastly, you could be one of those special apps which are running in the background, such as a voice over IP, audio, location, or a task completion process. In these situations, you'll use the Present Local Notification Now to deliver the notification as soon as that background event has been completed.
So now that we've talked through notifications, let's review some of the best practices we've covered for both push and local notifications. The first is don't overwhelm your users with notifications. Send them sparingly and only with information they need to know. Secondly, allow users to determine the notification events they want to receive. Give them the ability to customize which events are important to them, and they're more likely to stay engaged with your application.
Third, make sure to send the device token to your server on each of your application launches. This will ensure that you always have the latest device token that your users are using. Fourth, make sure to keep the connection open between your remote notification server and the Apple Push Notification Service between notifications. And lastly, remember to access the feedback service at least once a day to avoid sending notifications to users who are no longer using your app.
Now let's move on to the second half of our session and cover in app purchase. We'll talk about the architecture and implementation steps you'll need to understand to share an easy implementation. In app purchase is a powerful new feature that allows you to embed a store directly within your application utilizing iOS's store kit framework.
To begin, let's look at some examples of some developers who are doing some great things with in app purchase. It can be used to access pro features within your application. Here we have a popular camera app, and they're using in app purchase to offer different lenses to really expand the variety of pictures you can take with the application.
And they've created a beautiful storefront, which you can see is really compelling for the users. Another example of how in app purchase can be used is as in game currency. Here we have We Rule, and they use in app purchase to offer in game currency to allow users to build their farms faster and grow their crops faster.
Another example of how in app purchase can be used is to unlock services within the application. Here we have a popular GPS navigation app. However, the developers have offered an additional service via in app purchase, which is voice guidance. So upon making the purchase, you're now going to get voice navigation instead of having to look at your device. Proceed to the highlighted route.
In App Purchas can also be used to offer new content. This is very popular in magazines and newspaper applications and allows users to buy the latest edition as they come out within the application. And just launched, we now have Auto Renewing Content via In App Purchas. This allows you to set a time duration for a subscription, so users can subscribe once and receive updates to your application until that In App Purchas is consumed. Thank you.
To begin, let's talk about some of the features of in app purchase. And the first is that it uses the built-in framework store kit. This is the payment collection engine for iOS. The second great feature of in app purchase is for the developer. There are several benefits for you. The first being that the app store collects the payment for you.
You don't need to set up any sort of credit card processing system. You'll use the same infrastructure you use for your app purchases. And secondly, you'll receive the same great localized pricing and product details that you do with your regular applications. And lastly, you get the same great reporting in iOS. iTunes Connect as you do for your applications.
There are several customer benefits as well. The first is that they're greeted with a familiar purchase experience. They're using the same Apple ID and password they use to buy everything else they do from the iTunes Store. So therefore, they don't need to enter any payment information such as a credit card or billing address. And lastly, they'll still get the same App Store receipt provided via email, so they don't have to receive anything from different vendors.
Just like with notifications, there's three primary steps to implementing in app purchase in your applications. The first is to define your products. Secondly, you'll sell those products. And lastly, restore those products on new devices for users. In order to implement in app purchase, we're going to walk through these five steps. Determining product offerings, setting up those products in iTunes Connect, selling the products with the store kit framework, verifying the product receipts, and lastly, restoring previous purchases.
So first, let's determine our product offerings. When we determine product offerings, we need to figure out what we can and cannot sell within the application itself. For example, if we have a fitness application, we could sell videos of different lessons and workouts. However, we couldn't sell a membership to a gym down the street from within our application. Similarly, we could sell a digital book, such as the Odyssey. However, our application cannot sell the hard copy of that book itself. So, when you're thinking of the products you want to offer, remember that they have to be purchased and delivered within the application itself.
When we talk about in app purchase, there are four product types that you can choose from. The first is non-consumables. These are items that are purchased once and available forever. Second, we have our consumable items. These are purchased each time they are consumed, such as our in-game currency. Our third product type is Subscriptions. These are purchased each time the product expires, such as our magazine each edition buying a new one. And lastly, we have our new Auto Renewable Subscriptions. These are purchased at the end of each product duration period.
After we've determined the products we want to sell, we need to set them up in iTunes Connect for sale. And when we're in iTunes Connect, the first step you'll need is to make sure that you have a paid applications contract in effect. Even if your initial application is free, if you want to sell items from within it, you're going to need a paid apps contract.
After verifying that contract is in effect, you'll need to create your products list in the In App Purchases module within iTunes Connect. When you're setting up your product list, you'll provide each of those products with a unique name, a description, a price tier, and a unique product ID. It's important to remember that this product ID must be unique across all of your applications and items. So even if you're selling something similar within application A and application B, it needs to be a separate product ID for each of those sales.
Here we have an example of a developer who is trying to sell additional game levels within their application. They provided the necessary metadata, and now they'll ingest those into iTunes Connect for consumption. Once you've created that product list within iTunes Connect, you can now create a test user within iTunes Connect as well to test these purchases in the Sandbox environment.
It's important to remember this is not your Apple ID that you use to make purchases. This should be completely separate. And additionally, because each of these test users is tied to a specific store, you should create a separate user per country which you wish to sell your items in.
And lastly, as good practice, make sure to sign out of your store settings on your iOS device, especially when using the Sandbox. In order to do that, you'll navigate to the settings and sign out of any account you're in entirely. You don't want to enter your in app test user details into the store settings.
Now that we've set up our products in iTunes Connect, we're ready to sell these products using the Store Kit framework. The first thing we'll need to do to sell our products with StoreKit is to validate in app purchase access. We need to do this because installing purchased items can be prevented via parental controls in iOS. Therefore, we'll call the PaymentQueueClass method CanMakePayments. If we get back a value of yes, that means in app purchases are accessible and the user can make a purchase.
Once we've determined that they can make that purchase, we'll want to determine the sellable products we can offer to them. And to do so, we'll first load our potential product IDs from our app or server. And we'll take that potential product ID list and check it with StoreKit to determine the sellable subset of those IDs. And the sellable subset are those items that are entered into iTunes Connect and that have been cleared through AppReview.
StoreKit will give us back one of two responses, either invalid product identifiers or products. We'll want to build our store display from only those sellable products in the response.products. This means that iTunes Connect has validated that these products can be sold. After you've determined that sellable subset of your products, you can display your store.
And this is completely up to you. You can define how your store looks and feels. And all you need to do is include those response.products in your storefront. And additionally, since you've already entered all of this localized information into iTunes Connect, you can display products and pricing in the language and currency that users are used to seeing. And the price is always based on the user's iTunes store they're purchasing from.
Now that we've built our storefront and the user has decided they want to make a purchase, we'll request payment. And to do so, we'll use the SKPayment class to request that payment by first creating a payment object and then adding that payment object to a queue. And lastly, we'll observe that payment queue to know when the payment object has changed states.
When the user is making a purchase, they'll be presented with several different checkout process dialogues. These are going to be the same as they receive for app purchases. They'll first be asked to enter their account password. Next, they'll receive a purchase confirmation dialogue, and this will show the product and price of the item which they're purchasing in their localized string and currency.
If the item has already been purchased, they'll receive the Previous Purchase dialog. And lastly, when the payment has been successfully processed, they'll receive a Thank You dialog. One important note is that when you're testing in app purchases in the Sandbox, all of these dialogs will have the environment listed on it. So this will help in your debugging so that you can know exactly which environment you're trying to make purchases from.
Now that the customer has made a payment for our item, we'll need to complete the transaction. And to do so, we'll call the updated transactions method. We'll get back a transaction state which will determine whether or not the transaction has been completed. If we get back a state of purchased or restored, that means it was successful and we're ready to unlock the product for the user. After you've unlocked that product, you'll want to call Finish Transaction to complete the payment.
After finishing the transaction, you'll want to remember the product purchase and store those purchased items for the user. And you can do this in one of two ways. You can use an NSUserDefaults class to write a preferences file and save these to some application support directory. Or you can use the Keychain APIs and save these purchases to a secure Keychain slice owned by the application. You can use either of these methods to remember these product purchases.
Now that we've sold our products with StoreKit, we can verify the product receipts. In order to verify product purchases, we'll need two items. The first is a server that you operate, and secondly, we'll need the iTunes Receipt Validation Service. You may already have a server up and running to store your product IDs or managing your user accounts, so you can use that same server for verifying product purchases. This step is completely optional. You don't need to verify product receipts if you're not ready to. In order to verify product purchases, you'll first need to check the transaction receipt. Every purchase that you make will contain a signed receipt within it.
What you'll need to do is use your application to post a Base64 encoded transaction receipt to your remote server. Your remote server can then verify that transaction with the iTunes service and pass the response back to your application. Once your application has verified a successful purchase, you can unlock the product access.
Let's talk a little bit about how you'll post that receipt to the App Store to verify it. What you'll need to do is take your server and create a JSON object with this encoded transaction receipt. You'll post that to the iTunes Verification Service at one of these URLs. The first is the production environment, and the second is the sandbox.
The response you'll receive back from the iTunes Store is a JSON response. And as long as the status of that response is zero, that means the receipt was verified and that you can unlock the product. You can also inspect the receipt portion of that response for additional transaction details, such as product ID, app ID, app bundle ID, and purchase date.
The last step in implementing in app purchase is to restore previous purchases. You are required to restore subscription, auto-renewing subscription, and non-consumable items across all user devices. In order to restore previous purchases, you'll first need to determine the eligible items, such as subscription, auto-renewing subscription, and those non-consumable items. It's recommended that you provide a custom UI to your users, allowing them to restore all the purchases across the device. This makes it very simple for the user and for you.
Non-consumable and auto-renewing subscriptions can use the StoreKit Restore API to provide these items back. And by using the restore completed transactions, all the items a user has delivered can be restored to a new device. All that's required is that the customer signs in. And once they do so, we'll process it like a successful payment, and the user will receive the already purchased checkout dialog box. The customer will not be charged in this instance. If you're using subscription product types for in app purchase, you are required to provide your own mechanism for restoring these items.
Let's wrap up our discussion today with some in app purchase best practices. The first is that the paid applications contract is required. Even if your application is free and you want to sell items within it, you're going to need a paid applications contract in effect. Secondly, your product IDs that you define must be unique across all of your applications.
Thirdly, make sure to build your product display from sellable products only, not your entire product offering. Fourth, your in app purchase test user should not be an existing iTunes ID. You should set one up for every country that you plan to sell your products in. And lastly, remember to support the restoration of previous purchases across all of your users' devices.
If you need more information on any of these topics, you can contact Bill Dudney, the Applications Frameworks Evangelist, or consult the following documentation. In this session, we've covered two great features that you can start incorporating into your iOS apps today. By following the implementation steps and best practices we've discussed, and avoiding some of those common gotchas, you'll find your implementation experience significantly simplified, and you'll be delivering engaging apps to your customers in no time.