Push Notifications: Making your iOS client

Our Push Notifications system is currently in beta. This means you may experience errors, and the APIs may change. We would love to hear your feedback, so please get in touch!

Our Push Notifications system lets your iOS applications subscribe to interests. When your servers publish push notifications to those interests, the iOS app will receive them. Your iOS application can subscribe to interests using our Swift library or our Objective-C library on the push-notifications branch (the same libraries you use for WebSockets). This page guides you through setting up your iOS application to register, subscribe to interests, and receive push notifications pushed to those interests.

You should already have an iOS app which you would like to configure.
This guide is only compatible for iOS 10.0 or above.

For further exploring, the official Apple notification documentation is available here.

Setup the Podfile

Firstly, you’ll need to copy the following to your Podfile to enable Push Notification functionality:

pod 'PusherSwift'

pod 'libPusher', git: 'https://github.com/pusher/libPusher.git', branch: 'push-notifications'

Configure your AppDelegate

You should configure your app for push notifications in your AppDelegate. We’ll assume your app looks something like this, and initializes your Pusher instance early:

import PusherSwift
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var pusher: Pusher!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let options = PusherClientOptions(
            host: .cluster("YOUR_APP_CLUSTER")
        )
        pusher = Pusher(key: "YOUR_APP_KEY", options: options)
    }
}
#import <Pusher/Pusher.h>
@import UserNotifications;

@interface AppDelegate : NSObject <UIApplicationDelegate, PTPusherDelegate>
// ...
@property (nonatomic, strong) PTPusher *pusher;
@end

@implementation AppDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    self.pusher = [PTPusher pusherWithKey:@"YOUR_APP_KEY" delegate:self encrypted:YES];
    // ...
}
@end

Register with APNs

For your iOS app to receive push notifications, it must first register with APNs. You should do this when the application finishes launching, i.e. in its application:didFinishLaunchingWithOptions: handler. Your app should register for all types of notification, like so:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {    
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
        // Handle user allowing / declining notification permission. Example:
        if (granted) {
            application.registerForRemoteNotifications()
            pusher.connect()
        } else {
            print("User declined notification permissions")
        }
    }

    return true
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // ...
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
        if(!error) {
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        }
    }];  
}

Next, APNs will respond with a device token identifying your app instance. This device token is passed to your application with the application:didRegisterForRemoteNotificationsWithDeviceToken: method. Add a handler for it:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken : Data) {
    // ...
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // ...
}

Register with Pusher

Pusher requires the deviceToken in order to send push notifications to the app instance. Your app should then register with Pusher, passing along its device token. Add this to the above handler:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken : Data) {
    pusher.nativePusher.register(deviceToken: deviceToken)
    // ...
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [[[self pusher] nativePusher] registerWithDeviceToken:deviceToken];
    // ...
}

The call to pusher.nativePusher.register(...) is asynchronous: the app will register at some later time than when the call returns. However, you are able to subscribe to interests at any time, and these subscriptions will be logged with Pusher when the app registration completes.

Subscribe to an interest

Each interest name can be up to 164 characters. Each character in the name must be an ASCII upper- or lower-case letter, a number, or one of _=@,.;. Note that the hyphen (-) is not a valid character in interest names. This character is reserved for the possibility in future of marking interest names with prefixes (such as private- or presence-).

Let’s subscribe to an interest. Expand your handler to subscribe the app to the interest “donuts”:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken : Data) {
    pusher.nativePusher.register(deviceToken: deviceToken)
    pusher.nativePusher.subscribe(interestName: "donuts")
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [[[self pusher] nativePusher] registerWithDeviceToken:deviceToken];
    [[[self pusher] nativePusher] subscribe:@"donuts"];
    // ...
}

When your server publishes a push notification to the interest “donuts”, it will get passed to your app. This happens as a call to application:didReceiveRemoteNotification: in your AppDelegate. You should listen to this method:

func application(application: UIApplication, didReceiveRemoteNotification notification : [NSObject : AnyObject]) {
    print(notification)
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification {
    NSLog(@"Received remote notification: %@", notification);
}

If at a later point you wish to unsubscribe from an interest, this works in the same way:

pusher.nativePusher.unsubscribe(interestName: "donuts")
[[[self pusher] nativePusher] unsubscribe:@"donuts"];

For a complete example of a working app, see the Example/ directory in the pusher-websocket-swift library, or the Sample iOS/ directory in the libPusher library on the push-notifications branch.

You’re all set up! Next, we’ll actually send a push notification to the donuts interest, and your app will receive it. Let’s send some push notifications!

Have you tried using the search to find what you’re after? If you still have a question then get in touch with us and let us help you out.