Push Client Library - iOS

Urban Airship’s Push library provides a drop-in user interface for our Push Notification API. Our goal with this library is to enable developers to quickly and easily get started sending Apple Push Notifications to their device for testing

Our Push Sample application provides a reusable, drop-in settings UI and an interactive implementation of the library’s device token management capabilities that can be used as a testing and diagnostic tool to aid development.

Download

Push is available in two parts: a static library and an optional sample implementation.

We recommend everyone download the latest stable version.

Library: http://com.urbanairship.filereleases.s3.amazonaws.com/libUAirship-latest.zip

Sample App: http://com.urbanairship.filereleases.s3.amazonaws.com/PushSample-latest.zip

If you’re feeling brave you can download the latest development version of all our iOS code or you can check the code out with git:

git clone git://github.com/urbanairship/ios-library.git

The library and sample app are completely open source, so you may modify them as you wish. Patches and pull requests are always welcome.

Set Up a New Application

Copy libUAirship Files

Download and unzip the latest version of libUAirship. Copy the Airship directory into the same directory as your project:

cp -r Airship /SomeDirectory/ (where /SomeDirectory/YourProject/ is your project)

Required Libraries

Push requires your application to link against the following Frameworks (other sample UIs may have additional linking requirements):

libUAirship-<version>.a
AudioToolbox.framework (specific to the Push Sample UI)
MessageUI.framework (specific to the Push Sample UI)
CFNetwork.framework
CoreGraphics.framework
Foundation.framework
MobileCoreServices.framework
Security.framework
SystemConfiguration.framework
UIKit.framework
libz.dylib
libsqlite3.dylib
CoreTelephony.framework (this is iOS 4.x+ only, so make it a weak link for 3.x support)
StoreKit.framework

Build Settings

Header search path

Ensure that your project’s header search path includes the Airship directory (recursive).

_images/ios_header_search_path.png

Add UI Files

If you will be using the sample app’s UI in your application, add the Airship/UI/Default/Push folder to your project. To prevent errors, slow build times and unnecesasrily large executables, you should only add the sample UI folders that your application will be using.

Key Files

There are only a handful of files you’ll need to know to get started as a developer.

UAirship

This is the main singleton class that keeps track of global state.

UAPush

This class manages the device token and its associated properties. The header includes definitions for UAPushNotificationDelegate and UAPushUIProtocol, protocols that you can implement to use a custom UI.

Quickstart

Prerequisite

Before getting started you must perform the steps above outlined in Set Up a New Application.

In addition you’ll need to include UAirship.h and UAPush.h in your source files. If you are using the sample UI, you’ll need to include UAPushUI.h.

Airship API Setup

First, place your development and production keys and secrets in a file named AirshipConfig.plist. See The AirshipConfig File for details.

Inside your application delegate’s applicationDidFinishLaunching:application method initialize a shared UAirship instance:

//Init Airship launch options
NSMutableDictionary *takeOffOptions = [[[NSMutableDictionary alloc] init] autorelease];
[takeOffOptions setValue:launchOptions forKey:UAirshipTakeOffOptionsLaunchOptionsKey];

// Create Airship singleton that's used to talk to Urban Airship servers.
// Please replace these with your info from http://go.urbanairship.com
[UAirship takeOff:takeOffOptions];

[[UAPush shared] resetBadge];//zero badge on startup

// Register for notifications through UAPush for notification type tracking
[[UAPush shared] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                     UIRemoteNotificationTypeSound |
                                                     UIRemoteNotificationTypeAlert)];

To handle incoming notifications while the app is running:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    UALOG(@"Received remote notification: %@", userInfo);

    [[UAPush shared] handleNotification:userInfo applicationState:application.applicationState];
    [[UAPush shared] resetBadge]; // zero badge after push received
}

To properly clean up, call [UAirship land] on terminate:

- (void)applicationWillTerminate:(UIApplication *)application {
    [UAirship land];
}

Register for Push Notifications

Register for push notifications in application:didFinishLaunchingWithOptions:

// Register for notifications through UAPush for notification type tracking
[[UAPush shared] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                     UIRemoteNotificationTypeSound |
                                                     UIRemoteNotificationTypeAlert)];

Then, implement the callback that registers your new device token with Urban Airship:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Updates the device token and registers the token with UA
    [[UAPush shared] registerDeviceToken:deviceToken];
}

Badge Updates

The application’s icon badge can be manipulated with convenience methods provided by UAPush:

[[UAPush shared] setBadgeNumber:1];//set to 1
[[UAPush shared] resetBadge];//zero badge

A typical application will reset the badge any time a user starts the app or resumes it from the background. This can be done by making resetBadge calls from application:didFinishLaunchingWithOptions: and applicationDidBecomeActive. You may also wish to reset the badge after receiving a push when the application is running by calling reset from application:didReceiveRemoteNotification.

If your application uses Urban Airship’s autobadge feature, enable client-side autobadge tracking in application:didFinishLaunchingWithOptions: before changing the badge value:

[[UAPush shared] enableAutobadge:YES];
[[UAPush shared] resetBadge];//zero badge

This will ensure that the client will always sync badge changes with the server so that subsequent autobadge notifications will increment properly.

Launch Push Settings

Displaying the settings view is as simple as making a single call and passing in the view controller from which you wish to launch the Push Settings UI.

[UAPush openApnsSettings:parentViewController animated:YES];

Handling notifications

iOS handles push notifications received outside the application, but if a notification is received while the app is running, it is up to the application developer to handle it.

The sample UI includes an implementation of UAPushNotificationDelegate that handles alerts, sounds and badges, however if you wish to customize this behavior, you can provide your own implementation:

[UAPush shared].delegate = customPushDelegate;

Device Token Management

Aliases

A device-token alias allows you to assign a friendly name to your application install so that you can send push notifications to that device without storing a device token. See Push Notification API for more info about aliases.

New Alias:

NSString *alias = @"new_alias_string";
[[UAPush shared] updateAlias:alias];

Remove Alias:

[[UAPush shared] updateAlias:nil];

Tags

Tags are an easy way to group device tokens. Unlike aliases, of which you can only have one (though a single alias can apply to many device tokens), many tags can be applied to one or more device tokens. Then, a message sent to a tag will be sent out to all device tokens that are associated with that tag.

Tags are a good way to group device tokens by country, language, time zone or device type. These tags can be automatically generated using UATagUtils.

Add a single tag:

NSString *tagToAdd = @"a_tag";
[[UAPush shared] addTagToCurrentDevice:tagToAdd];

Remove a single tag:

NSString *tagToDelete = @"a_tag";
[[UAPush shared] removeTagFromCurrentDevice:tagToDelete];

Set the current list of tags using UATagUtils:

// Set some commonly used tags
NSArray *tags = [UATagUtils createTags:
                                      (UATagTypeTimeZoneAbbreviation
                                          | UATagTypeLanguage
                                          | UATagTypeCountry
                                          | UATagTypeDeviceType)];

 [[UAPush shared].tags = [NSMutableArray arrayWithArray:tags];//update locally
 [[UAPush shared] updateRegistration];//update server

Quiet Time

Often end users don’t want to receive push notifications at certain times, such as when they’re asleep. Urban Airship supports setting a “quiet time” via the device registration API during which time no push notifications for your app will be delivered to that device token. Push notifications containing a badge update will still be sent during quiet time, but the alert and sound will be removed.

To set quiet time:

NSDate *fromDate;//set with the hour and minute quiet time begins
NSDate *toDate;//set with the hour and minute quiet time ends

[[UAPush shared] setQuietTimeFrom:fromDate to:toDate withTimeZone:[NSTimeZone localTimeZone]];

The User Interface

The Push Settings Interface

The push settings interface provides controls for toggling push notification and managing quiet time. Drop this interface directly into your application to give your users control over these settings.

The following is an example of how you can launch the settings from a button press in your view controller:

- (IBAction)buttonPressed:(id)sender {
    if (sender == settingsButton) {
        [UAPush openApnsSettings:parentViewController animated:YES];
    }
}

The Token Settings Interface

The Token Settings interface provides a view into the current state of a device token and is designed to help you diagnose potential problems with your setup.

There are fields:

Notification Types

Shows the types of notifications for which your application has successfully registered.

Disabled Notification Types

Shows the notification types that the application requested, but the user disabled.

Device Token

A 64 character string representation of your application’s device token assigned by Apple.

If this field is blank you will not receive push notifications. Here are some possible reasons for the Device Token to be blank:

  • Your application cannot contact Apple (e.g., network connectivity issues).
  • You’re running your application in a simulator.
  • Your application key is incorrect.
  • You have not set up your push notification certificate. (see Exporting Your Push Notification Key)

In the device token detail view, you can copy the device token to the clipboard or send it in an email message.

Alias

Shows the current alias, or “Not Set” if there is not an alias registered for this device token. Open the detail view to modify the alias.

Tags

Shows the device’s current tags. Open the detail view to modify the list and view the tags suggested for this device by UATagUtils.

Notification Sounds

Displays a list of the sounds currently bundled with the application. Tap the name to play the sound.

Localization

The Push sample has built-in localization support. All Urban Airship localization strings for Push settings are contained in their own bundle:

UAPushLocalization.bundle

To add a new translation just copy one of the existing lproj directories into the bundle and update all of the items in Localizable.strings

Sending your first notification

Now that your device is ready to receive push notifications you can login to https://go.urbanairship.com and click on the test push notifications link. If you haven’t already set up your application’s push notification certificate and uploaded it to the Urban Airship control panel you will need to do so at this time. For more info about configuring your application see Exporting Your Push Notification Key.

Sound Notifications

The test application is bundled with 4 test sounds. To send a sound notification to the test application you can use any of the following:

  • pig
  • cat
  • cow
  • frog

You can test your own custom sounds simply by adding your sound files to the test application and reinstalling it on your device. Your sound files just have to be in the main application bundle.