11. Newsstand Kit

The last chapter of this book focuses on a new type of app available on iOS devices starting with iOS 5. Newsstand apps are designed to provide magazine, newspaper, and other subscription-based periodical content a unique platform and special place in the App Store. Starting with iOS 5, Newsstand apps are available in a special bookshelf folder on all iOS devices—sort of like a virtual magazine rack. When new content is available, these apps have the ability to automatically download the latest issue (in the background), post a badge indicating the number of new issues, and even change the app icon to reflect the new content. All of this is made possible with a new framework called Newsstand Kit.

Getting Started with Newsstand Kit

The Newsstand Kit framework provides a central library for storing and managing publication issues locally on a device. Additionally, Newsstand Kit creates easy to use hooks into system APIs for managing content downloads when your app is not running. Before we get into the specifics of how Newsstand Kit works, however, there are a few settings you need to configure in your app to make it a Newsstand app.

As mentioned, Newsstand apps get special treatment in both the App Store and on the iOS home screen. Specifically, these apps are separated from the pack and, unlike traditional iOS apps, developers can programmatically change Newsstand app icons after the app is installed on a device. This process of changing icons can be done in the background when the app is not running and is often used to indicate new content to a user. Further, Newsstand app icons are not limited to a square aspect ratio but can be any height to width ratio based on the paper size of your publication (Figure 11.1).

Image

Figure 11.1. The Newsstand section on the iOS home screen.

Setting Up a Newsstand App

Because of these and other special considerations given to Newsstand apps, there are three key steps you must follow before your app will be listed in the Newsstand section of the App Store. These steps are

1. Linking the NewsstandKit framework to your project in Xcode and importing <NewsstandKit/NewsstandKit.h> in the header (.h) files that use the Newsstand Kit APIs.

2. Modifying your app’s info.plist file with the appropriate Newsstand Kit metadata flags.

3. Identifying your app as a Newsstand app in iTunes Connect.

Newsstand App Info Property List Changes

As you know, an app’s info property list (named MyApp-Info.plist in Xcode) contains all of the configuration information of an iOS app. When working with Newsstand apps, you must add specific values to this property list before your app will be identified as a Newsstand app.


image Note

The following section demonstrates how to edit the info property list using Xcode 4, which provides a special section for an app’s settings. If you’re using Xcode 3.2, you’ll need to select the info.plist file and add these values manually. For more information, visit iOSCoreFrameworks.com/reference#xcode-3-2.


There are three keys that you need to add to your app’s property list. Add these properties by clicking your project icon at the top of Xcode’s left navigation panel, selecting your target, and then selecting the Info tab. To add a new row to your property list, simply right click and select Add Row.

Depending on how your property list is set up, you’ll either see raw key and values, or a human-readable summary of the key. You can toggle between these settings by right clicking the property list as shown in Figure 11.3.

Image

Figure 11.3. The app info property list in Xcode.

The following three raw keys need to be added to your property list (I’ve also indicated the human-readable versions for each key). If your property list is set to show the human-readable keys and values, you can add a new key using either the raw or human-readable version. However, if your property list is set to show the raw key values, you’ll need to add the key based on the bold raw key value.

UINewstandApp: The UINewsstandApp key is a Boolean value that tells iOS whether or not an app should be listed in the special Newsstand section on the iOS home screen. You should set this value to YES to create a Newsstand app. The human-readable version of this key is Application presents content in Newsstand.

CFBundleIcons: The CFBundleIcons key is new to iOS 5 and contains a dictionary of icon styles. This dictionary will include by default CFBundlePrimaryIcon (which is the old icon property list key) and UINewsstandIcon. For CFBundlePrimaryIcon, you can just copy and paste in your existing icon plist values. The UINewsstandIcon dictionary contains three important objects: the binding type (Magazine or Newspaper), the binding edge (left, bottom, or right), and an array of icon files used as the default cover in Newsstand. The human-readable version of this key is Icon Files (iOS 5).

UIBackgroundModes: The final key you need to add to your property list is actually not new to iOS 5—the value inserted, however, is. UIBackgroundModes tells iOS for what reasons your app is allowed to run in the background. For example, in iOS 4 this key could be used to allow your app to play music or provide Voice over IP services. For Newsstand apps, we need to tell iOS to wake up our app in the background when new content is available and an issue needs to be downloaded. The key for this service is newsstand-content. The human-readable version of this key is Required background modes.

At this point, your property list should look something like the property list in Figure 11.4. The next step is to configure your app in iTunes Connect.

Image

Figure 11.4. Example Newsstand app property list.

Creating a Newsstand App in iTunes Connect

Now your Xcode project is ready to work with Newsstand and will display Newsstand apps on your test devices. In the interest of completeness when setting up a Newsstand app, however, there are some steps you need to take in iTunes Connect before you actually submit your app for review.

After creating your app in iTunes Connect, you need to enable the app for Newsstand. Simply log into iTunes Connect, select your app, and then choose the Newsstand option listed on the right-hand side (Figure 11.5). Once enabled, you have the option of identifying issue information and default icons to be used to represent your Newsstand app in the iTunes App Store.

Image

Figure 11.5. Enabling Newsstand in iTunes Connect.


image Tip

Once your app is released, you’ll want to continually add new information to iTunes Connect so that the App Store can reflect the most recent information. You do not, however, have to manage this process manually! You can configure a special ATOM feed to automatically feed this information into iTunes Connect. Visit iOSCoreFrameworks.com/tutorial#newsstand-atom for a quick tutorial on how to configure this ATOM feed.


Understanding Newsstand Apps

Now that your Xcode project is configured for a Newsstand app, you’re probably ready to jump right in and start coding—not so fast. First, it’s a good idea to gain a solid grasp of how Newsstand actually works, what paths the information follows, and what information you as a developer need to track so that you can notify your users of new content.

Newsstand Kit Library and Issues

Remember that Newsstand is designed as a repository for publications, and more specifically, publications with periodical content like magazines and newspapers. The Newsstand Kit and its components were built from the ground up with these analogies and best practices in mind.

When building a Newsstand app, your content should easily be broken into issues. A magazine app might have a new issue every month, while a newspaper app might have a new issue every day. Each of these issues will be stored in a central library that can be accessed through the Newsstand Kit APIs. Appropriately, in Newstand Kit this central library is called NKLibrary (Newsstand Kit Library) while the individual issues are called NKIssues (Newstand Kit Issues).


image Note

There is a third object type important to Newsstand Kit called NKAssetDownload. While NKIssues represent completed issues and NKLibrary represents where issues are stored, NKAssetDownloads represent issues that are currently being downloaded. We’ll cover these in more detail in the section below, Downloading Newsstand Kit Content.


Newsstand Kit Library

The Newsstand Kit Library (NKLibrary) is singleton-based, meaning each Newsstand Kit app has one and only one NKLibrary. You can obtain a reference to your app’s NKLibrary by calling [NKLibrary sharedLibrary].

The NKLibrary is an incredibly basic object, having only three purposes: track all issues stored on a device, track all downloads currently in progress, and track which issue a user is currently reading. The following code block demonstrates these three scenarios:

 1   // Obtain a reference to the NewsstandKit Library
 2   NKLibrary *library = [NKLibrary sharedLibrary];
 3
 4   // Get a list of all issues in the library
 5   NSArray *allIssues = [library issues];
 6
 7   // Get a list of all issues being downloaded
 8   NSArray *pending = [library downloadingAssets];
 9
10   // Set the users current issue
11   [library setCurrentlyReadingIssue:myCurrentIssue];

As you can see in this code block, once you have a reference to your library you’re ready to start working with individual issues.

It’s important to note that the NKLibrary only tracks the issues currently on your device. If an issue is deleted (which iOS might do automatically if your device is running low on space), your NKLibrary will no longer know about that issue. This means your UI should not be designed around issues available in the library, but rather issues available for download. Once downloaded, you pull the issues from your library for use. You can store this list using Core Data as we learned in Chapter 2, Core Data, or through other means.

Newsstand Kit Issue

The Newsstand Kit Issue (NKIssue) is the data structure that represents your content inside of Newsstand Kit. Every issue has two defining properties: a unique name and a published date.

An issue name can be almost anything, but it should be completely unique across all of your issues. When you reference issues from the NKLibrary, you do so by calling [library issueWithName:@"MyIssueName"]. An issue name can be the unique ID of the issue stored in an external content management system, or something more descriptive like “MyIssue1”. The only limitation is that the name be unique so that you can obtain an NKIssue reference from your library. The date associated with the issue should be the publish date of your content.

Downloading Newsstand Kit Content

Now that you understand how Newsstand apps store and access information, it’s time to start downloading content. When you download a new issue, you don’t have to worry about where to store it in the app’s file system. Instead, iOS will automatically create a unique folder for that issue located in your app’s Caches folder found at ~/Library/Caches/Newsstand.

Remember, the ~/Library/Caches folder (and its subfolders) are not backed up when a device is synced to iTunes or synced with iCloud backup. This means that if a user restores their device, all of their downloaded issues will be lost.

Additionally, starting with iOS 5, when your device is running low on space, an automated process might clean up an app’s Caches folder, because the content in the Caches folder can be easily redownloaded. While this practice might be revisited in the future, for now you should never assume that once an issue is saved to the device its content will always be available. As a best practice, you should maintain a list of available issues outside of your library using either Core Data or a whitelist of sorts saved in your app’s Documents folder. If you’re selling issues through a subscription service and your users should be allowed to download issues if lost, you should store which issues should be allowed for redownload and design your app’s UI and user workflows accordingly. You may need to redownload an issue in some situations.

Note: iOS will not delete an issue’s cache content if it’s indicated as the issue currently being read in the library.

Do not attempt to store the actual issue content outside of the Caches folder expecting iTunes to back it up. This content is lost by design since it can be easily redownloaded from your website. If necessary, you should simply store a list of issue names that the user will be allowed to download. Otherwise, if your app attempts to store your issue content outside of the Caches folder, it may be removed from the App Store for violating the Data Storage Guidelines of iOS 5.


image Tips

For more information on the iOS Data Storage Guidelines, visit iOSCoreFrameworks.com/reference#data-storage.

Newsstand content downloads can be any file type. However, it’s highly recommended that you set up your content download as a zip file or some other compressed media. Then, when your download is finished, you should extract the files to the appropriate Caches directory. This is ideal because iOS only has to track one download per issue and you can still bundle as many files in your issue bundle as needed.


Starting a New Download

To download new Newsstand content, you need to follow these four steps:

1. Check your library and make sure you don’t already have the issue you’re trying to download.

2. Add a new issue to the library with the name and date of your new issue.

3. Create an NKAssetDownload object with the URL of the content you want to download for this issue and add it to the issue created in Step 2.

4. Call downloadWithDelegate on the newly created NKAssetDownload created in Step 3.

The following code block demonstrates a method designed to download a new issue. In this example, we’re assuming the parameter info contains a dictionary of information needed for our download. In this scenario, we would call this method after our app has queried an external website to pull the most recent issue information. The response from that website was a dictionary containing the newest issue name, pubdate, and URL for the issue assets.

 1   - (void)downloadIssueWithInfo:(NSDictionary *)info{
 2      NSString *contentURL = [info objectForKey:@"contentURL"];
 3      NSDate *pubdate = [info objectForKey:@"pubdate"];
 4      NSString *name = [info objectForKey:@"issueName"];
 5
 6      //Get a reference to our library
 7      NKLibrary *library = [NKLibrary sharedLibrary];
 8
 9      //Only try to download the issue if we don't already have it
10      if(![library issueWithName:name]){
11        NKIssue *issue = [library addIssueWithName:name date:pubdate];
12
13        //Create our request to start the download
14        NSURL *assetURL = [NSURL URLWithString:contentURL];
15        NSURLRequest *request = [NSURLRequest requestWithURL:assetURL];
16
17        // Create an NKAssetDownload with our download URL
18        NKAssetDownload *asset = [issue addAssetWithRequest:request];
19
20        // Set the asset User Info dictionary to some custom value
21        // This step is optional, but when the asset is finished
22        // downloading you can use the UserInfo dictionary to pass
23        // important info like filenames, etc., that might be needed
24        [asset setUserInfo:info];
25
26        // Important! Now we need to actually start the download
27        [asset downloadWithDelegate:self];
28     }
29   }

In lines 2 through 4 we simply pull out the three key properties of our new issue. How you obtain these values is completely up to you. Here, as mentioned, it’s assumed that the information is provided in the info dictionary. Next, in line 10 we first check to see if our library already contains an issue for the name provided. Issue names are unique; if the library already has an issue for that name, we shouldn’t try to download it again.

In line 11, we create a new NKIssue by adding an issue to the library with the name and published date provided. Now, at this point our library contains our issue, but it’s completely empty. The next thing we need to do is actually download the issue assets so iOS can store them in the Caches folder. In lines 13 through 18 we create an NKAssetDownload object. Notice the NKAssetDownload is initialized using an NSURLRequest. So, in lines 14 and 15 we create an NSURLRequest from the asset URL provided in our info dictionary.

Line 24 is an optional step, but something you will find valuable in practice. Eventually, your asset will finish downloading and will be stored in the Caches folder. Depending on how your app is set up, you might need additional information about your asset besides the name, pubdate, and content URL. The user info dictionary of an asset is your opportunity to set these values so they can be retrieved later. In this example, we set the user info dictionary to our info parameter.

Finally in line 27 we start the asset download by calling downloadWithDelegate. In this example we used the delegate self, which means the class that implements this method also implements the protocol NSURLConnectionDownloadDelegate. This is important because when the asset is finished downloading, it will call connectionDidFinishDownloading:destinationURL on this delegate method.


image Tip

You can download a working example of this project and more at iOSCoreFrameworks.com/download#chapter-11.


Handling Download Progress and Finished Downloads

When an NKAssetDownload is started, it’s done so with a download delegate that implements the NSURLConnectionDownloadDelegate protocol. Now, the NKAssetDownload actually uses the same NSURLConnection protocol that’s found throughout iOS—remember that we simply initialized the asset download using a normal NSURLRequest, just like NSURLConnection. In fact, in iOS 5 NSURLConnection was extended to let developers obtain an NKAssetDownload reference from its corresponding NSURLConnection.

So what does this mean? This means that when you start a new asset download, your delegate should implement the appropriate methods found in Table 11.1.

Table 11.1. NSURLConnectionDownloadDelegate Protocol

Image

When a download is finished, it calls connectionDidFinishDownloading on the delegate. However, the file created is only a temporary file. At this point, it’s your responsibility to move the file into the appropriate issue folder on the file system. Your newly downloaded file is only guaranteed to exist during the execution of this connectionDidFinishDownloading method.

The following code block demonstrates how to move your newly downloaded file to the appropriate directory. In this example, we’re assuming that the user info dictionary contains the download’s filename for the key "filename". Remember in the last section, setting the user info dictionary is optional, so if you don’t store the filename here, you should do so elsewhere.

 1   - (void)connectionDidFinishDownloading:(NSURLConnection*)connection
                             destinationURL:(NSURL *)destinationURL{
 2     // Get a reference to our NKAssetDownload and NKIssue
 3     NKAssetDownload *asset = [connection newsstandAssetDownload];
 4     NKIssue *issue = [asset issue];
 5
 6     // Get the filename of our issue download from the user info
 7     NSString *filename = [[asset userInfo] objectForKey:@"filename"];
 8
 9     // Get the path of Issue's folder at ~/Library/Caches/Newsstand
10     NSURL *issueURL = [issue contentURL];
11     NSURL *toURL = [issueURL URLByAppendingPathComponent:filename];
12
13     // Move the downloaded asset to our issue folder
14     NSError *error = nil;
15     NSFileManager *fileManager = [NSFileManager defaultManager];
16     BOOL success = [fileManager moveItemAtURL:destinationURL
                                           toURL:toURL
                                           error:&error];
17     // If for some reason we failed to move the issue, tell us why
18     if(!success)
19       NSLog(@"%@",[error localizedDescription]);
20
21   }

Here is an example of how to handle the connectionDidFinishDownloading method in your NSURLConnectionDownloadDelegate. In lines 3 and 4 we obtain a reference to our NKAssetDownload and NKIssue objects. Notice that in line 3 we can simply retrieve the NKAssetDownload directly from the NSURLConnection. Next, in line 7 we pull out the filename of our download from the asset’s user info dictionary. Remember in the last section that setting this property is optional; this is just one of the reasons why having additional information in the user info dictionary might be valuable. While it’s certainly not required, as you can see it does make some operations much easier.

Because the downloaded file is only temporary, we need to move it into the appropriate issue folder in our Caches directory. To do this, first we need to get the destination URL on the file system. All NKIssues retain a reference to their specific asset folder in the Caches directory. In line 10, we get a URL of this directory by calling [issue contentURL]. Next, since we’ll be moving a file to that directory, we append our filename as a path component.

Finally, we move the downloaded file from its current location to the new location. Lines 14 through 16 perform this move action by using the NSFileManager. In line 16, notice that the destinationURL is the parameter provided in our connectionDidFinishDownloading call and represents where the temporary file was saved. The toURL is our newly created path in the issue’s cache folder. For good measure, in lines 18 and 19 we catch an error just in case the move operation was unsuccessful.


image Tip

You can download a working example of this project and more at iOSCoreFrameworks.com/download#chapter-11.


Updating the Appearance of a Newsstand App to Reflect New Content

Remember that you as a developer have the ability to update a Newsstand app’s icon and badge count to indicate new material. This should only be done after new content is finished downloading, so an ideal place to change your icon is in the connectionDidFinishDownloading method in your download delegate.

The following code block demonstrates how to change the app icon to reflect our new cover. Here, newCover is assumed to be an image that was just downloaded as a part of this issue.

1   UIApplication *application = [UIApplication sharedApplication];
2   [application setNewsstandIconImage:newCover];
3   [application setApplicationIconBadgeNumber:1];

In line 1 we obtain a reference to our shared application. Next, in line 2 we call setNewsstandIconImage to change our cover image. Remember, this image does not need to be the same square aspect ratio of app icons, but can be any height to width ratio as needed by your cover. Finally in line 3 we set the badge number to help identify users of new content.

Notifying Newsstand Apps

One of the key features of Newsstand apps is their ability to download content in the background—even when your app is not running. This is accomplished by using a few different technologies in combination with core system APIs. When new content is available, Newsstand apps are notified using the Apple Push Notification Service.

Using Apple Push Notification Service

Apple Push Notification Service (APNS) is used to send notifications to iOS apps. When an app launches, developers have the opportunity to register that app to receive notifications. In the past, these notification types included text alerts, badge alerts, and sound alerts. Starting with iOS 5 there is a new alert type, Newsstand Content Availability.


image Note

You’ll need to make sure your app is configured for push notifications in the iOS Provisioning Portal before you can send and receive push notifications. For a complete tutorial on how to set up the APNS side of this equation, visit iOSCoreFrameworks.com/tutorial#apns.


If you’ve never used APNS before, the service works as a three-stage system. When an app launches, the developer registers the device to receive notifications. If a user approves the notification, the developer is given a unique device token used to represent that device. The developer should store this device token in a database on their own website, external from the iOS app. When a new notification is ready, your website sends the message to Apple’s push notification servers which in turn delivers the notification to the appropriate device. Figure 11.6 illustrates this workflow.

Image

Figure 11.6. Apple Push Notification workflow.


image Note

The iOS Simulator cannot receive remote notifications. If you want to test remote notifications, you’ll need to do it on an actual iOS device.


Registering for Newsstand Update Notifications

Before you can receive Newsstand update notifications through APNS, you need to register your app to receive notifications. You can do so by calling registerForRemoteNotificationTypes: in the applicationDidLaunch method of your app delegate. The notification type for Newsstand updates is UIRemoteNotificationTypeNewsstandContentAvailability.

1   [application registerForRemoteNotificationTypes:
                 UIRemoteNotificationTypeNewsstandContentAvailability];

When registering for remote notifications, you need to implement three methods in your application delegate:

application:didRegisterForRemoteNotificationWithDeviceToken:

application:didFailToRegisterRemoteNotificationWithError:

application:didReceiveRemoteNotification:

iOS will call these methods on your app delegate throughout the notification process. As mentioned, in the first method listed you will need to save the device token in an external database. The last method listed will be called when your APNS sends a new notification to your device. For Newsstand, this is where you would check for the latest issue information and download if necessary.

Unlike normal push notifications, iOS devices can and will only receive a Newsstand Content Available notification once in a 24-hour period. If your server attempts to notify devices more frequently than once every 24 hours, the notifications will simply be ignored and your didReceiveRemoteNotification will not be called.


image Tip

You can turn off the once-per-24-hour limit by setting a Boolean value of YES to your NSUserDefaults for the key NKDontThrottleNewsstandContentNotifications. However, this will only turn off throttling for apps running on your development devices. Once your app is launched in iTunes, notifications will be limited to once per 24 hours.


Newsstand Push Notification Format

Apple Push Notifications are very short and concise. The APNS message is called a payload and is delivered as a JSON formatted dictionary. In iOS 4, this payload was structured as follows:

{
      "aps" : {
           "alert" : "Text body of the alert message",
           "badge" : 1,
           "sound" : "customSound.aiff"
      }
}

Each key in the aps dictionary represents data for each remote notification type. The alert key value represents the text shown in an alert dialog, the badge key value indicates the badge count of your app, and the sound indicates the sound played when the alert comes in. Starting with iOS 5, there is a new value/key pair available in the aps dictionary, "content-available".

It’s not required that your payload include all of the value/key pairs available. In fact, if your app is strictly a Newsstand app and you do not support any other push notification types, then your payload will simply look like this:

{
      "aps" : {
            "content-available" : 1
       }
}

This payload, when sent to APNS, would notify an app that new content should be downloaded for Newsstand. The content of this payload is passed into your app’s didReceiveRemoteNotification method.

Responding to Remote Notifications

When your app receives a remote notification through APNS, iOS automatically calls the appropriate delegate methods. Remember, this notification is simply a Boolean value telling your app if content is available. After receiving a new notification, the responsibility is still on your app to query your servers, find the most recent issue information, and download new issues if necessary.

Realize that you do not have an unlimited amount of time to perform these steps. When your app receives a notification, your app only remains active for a few seconds. During that time you either need to start the NKAssetDownload (which is run by the system, not your app) or dispatch a long background process using an expiration handler.


image Tip

For more information on running long background processes with an expiration handler, visit iOSCoreFrameworks.com/reference#long-process.


The following code block demonstrates how to respond to a local notification.

 1   - (void)application:(UIApplication *)application
 2       didReceiveRemoteNotification:(NSDictionary *)userInfo{
 3
 4       // Get our aps dictionary from the APNS payload
 5       NSDictionary *aps = [userInfo objectForKey:@"aps"];
 6
 7       // If content is available, get the latest issues
 8       if([aps objectForKey:@"content-available"]){
 9           [self getLatestIssueInfo];
10       }
11   }

Here we have a very easy implementation of didReceiveRemoteNotification. Remember that when this method is called, iOS will send the APNS payload as a dictionary named userInfo. In line 5 we pull out our aps dictionary from the payload and in line 9 (if the payload contains information that new content is available for download) we get the latest issue info.

If our “get latest issue info” call is a long process, you should set it up as a background process with an expiration handler. For this example, however, we’re assuming this process is short and that when it completes, it will call downloadIssueWithInfo as seen in the previous section.

Special Considerations with Newsstand Apps

There are a few gotchas when working with Newsstand apps. If your app is not running when a push notification is received, your app needs to be configured to handle this condition. Additionally, iOS is responsible for handling all of the NKAssetDownloads; if for some reason the user quits your application while this download is in progress, you need to reconnect the download to your application.

Newsstand Apps Waking Up from Background

You may have noticed that all of these delegate calls are made on the application delegate. What happens if your app is not running? Obviously there will be no app delegate to handle the call if your app has quit. This is why we enabled the UIBackgroundMode to allow newsstand-content. If your app is configured to allow the UIBackgroundMode newsstand-content, iOS will restart your app in the background.

When your app is restarted under this condition, iOS will call the method applicationDidFinishLaunching, just like it has always done. However, the launchOptions parameter provided in this call will contain the APNS payload that was missed—because your app was not running and the app delegate could not call didReceiveRemoteNotification.

For this reason, when your app first launches you should check the launchOptions dictionary to see if you’re launching because of a missed APNS notification. If you are, you should call didReceiveRemoteNotification yourself to handle any additional operations.

The following code block demonstrates how to handle an application launch caused by a missed APNS notification. Notice the APNS payload is stored in our launch dictionary for the key, "UIApplicationLaunchOptionsRemoteNotificationKey".

1   if([launchOptions valueForKey:
            @"UIApplicationLaunchOptionsRemoteNotificationKey"]){
2     NSDictionary *payload = [launchOptions objectForKey:
            @"UIApplicationLaunchOptionsRemoteNotificationKey"];
3     [self application:application
            didReceiveRemoteNotification:payload];
4   }

This code block is a little hard to read because of the brevity exercised by the Apple engineering team (can you tell that was sarcastic?), however, the practice is simple. All we’re doing is first checking to see if the launch dictionary contains a value for the key UIApplicationLaunchOptionsRemoteNotificationKey (line 1). If the launch dictionary contains a value for this key, we pull it out and store it as a payload dictionary (line 2) and then call didReceiveRemoteNotification on our self in line 3 passing in the payload as a parameter.

Reconnecting Abandoned Asset Downloads

One of the nice things about Newsstand Kit is that when you start a download, you really don’t have to do anything to manage its progress; iOS hands the process off to the same system background download queue used for downloading apps, music, and so on. When you start a download, remember you first created an NKIssue, then attached the download to that issue and set the download delegate. In an ideal world, the download delegate is called when the download finishes and everything proceeds as normal.

However, it’s entirely possible that while your download is happening, your app will be quit by the user and the delegate responsible for handling the connectionDidFinishDownloading method will be destroyed. Fortunately, your NKLibrary will keep track of all downloads that are currently in progress or pending.

For this reason you should always reconnect any pending downloads in your NKLibrary to your download delegate on application launch. You can do this very simply with a few lines of code.

1   NKLibrary *library = [NKLibrary sharedLibrary];
2   for (NKAssetDownload *asset in [library downloadingAssets]){
3       [asset downloadWithDelegate:self];
4   }

In this code block we obtain a reference to our NKLibrary in line 1 and then in lines 2 through 4 we iterate through all of the downloading assets in that library and reassign the download delegate to self.

You should always reconnect your downloads at launch. This should be one of the first things done in a Newsstand app. If you don’t reconnect any abandoned downloads, iOS will complete the download and not call a delegate method—which means the file will simply be deleted from the Caches folder. But since you already created the issue in your NKLibrary, you’ll then have a condition where you have an issue and no content. By reassigning the delegate when your app first launches, you make sure that no downloads are abandoned.

Wrapping Up

And that’s it. There really isn’t much to creating a Newsstand app. Once you have your content stored as issues in your library, you can simply retrieve those issues from the library and use your content as you’ve always done.

Remember, you should really only be using Newsstand Kit if your app is a publication and your content can easily be separated out into issues. Additionally, Newsstand uses APNS to notify apps that content is available. This push notification does not actually contain the issue information, but instead tells your app to check your servers and download the latest issue information. If needed, your app should then download the necessary information. When finished downloading you can easily change the app icon and badge count indicating new content is available to users.

Finally, when your app first launches you should always perform the following actions:

1. Check to see if your app launched because of a missed remote notification.

2. Reconnect any asset downloads from your library to your download delegate.

Newsstand apps are an entirely new class of application for iOS and have rewritten the rules for periodical content. By taking advantage of this new framework in iOS 5, you can easily push new content to your users with very little effort on the side of both the user and the developer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.45.137