Documentation

Handle Notifications


Declare a callback within your AppDelegate class to listen for incoming notifications.

As soon as the user interacts with your notification by either swiping or clicking on it, or in case your app is in the foreground, your listener will be invoked and your app can then execute any relevant action in response, such as playing a sound, displaying the relevant storyboard, making a request, etc.

Please select your project type for the appropriate instructions:

Swift
Objective-C

Add the following within the AppDelegate class, after pushy.register():

// Handle push notifications
pushy.setNotificationHandler({ (data, completionHandler) in
    // Print notification payload data
    print("Received notification: \(data)")

    // Fallback message containing data payload
    var message = "\(data)"
    
    // Attempt to extract "message" key from APNs payload
    if let aps = data["aps"] as? [AnyHashable : Any] {
        if let payloadMessage = aps["alert"] as? String {
            message = payloadMessage
        }
    }
    
    // Display the notification as an alert
    let alert = UIAlertController(title: "Incoming Notification", message: message, preferredStyle: UIAlertControllerStyle.alert)
    
    // Add an action button
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
    
    // Show the alert dialog
    self.window?.rootViewController?.present(alert, animated: true, completion: nil)
    
    // You must call this completion handler when you finish processing
    // the notification (after fetching background data, if applicable)
    completionHandler(UIBackgroundFetchResult.newData)
})

Add the following within AppDelegate.m, after [pushy register]:

// Handle push notifications
[pushy setNotificationHandler:^(NSDictionary *data, void (^completionHandler)(UIBackgroundFetchResult)) {
    // Print notification payload data
    NSLog(@"Received notification: %@", data);
    
    // Fallback message containing data payload
    NSString *message = [NSString stringWithFormat:@"%@", data];
    
    // Attempt to extract "message" key from APNs payload
    if (data[@"aps"]) {
        NSDictionary *aps = [data objectForKey:@"aps"];
        
        if (aps[@"alert"]) {
            message = [aps valueForKey:@"alert"];
        }
    }
    
    // Display the notification as an alert
    UIAlertController * alert = [UIAlertController
                                    alertControllerWithTitle:@"Incoming Notification"
                                    message:message
                                    preferredStyle:UIAlertControllerStyleAlert];
    
    // Add an action button
    [alert addAction:[UIAlertAction
                        actionWithTitle:@"OK"
                        style:UIAlertActionStyleDefault
                        handler:nil]];
    
    // Show the alert dialog
    [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
    
    // You must call this completion handler when you finish processing
    // the notification (after fetching background data, if applicable)
    completionHandler(UIBackgroundFetchResultNewData);
}];

Make sure to invoke the completionHandler with an appropriate UIBackgroundFetchResult when you're done processing the notification.

Note: This listener will be invoked in the background, without requiring user interaction, if you send the content_available flag with your push notifications, as documented in the Send Notifications API.

Parse Notification Data


Any payload data that you send with your push notifications is made available to your app via the data parameter of the setNotificationHandler callback.

If you were to send a push notification with the following data payload:

{"id": 1, "message": "Hello World!"}

Then you'd be able to retrieve these values in your setNotificationHandler callback like so:

// Safely unwrap "id" parameter (Int)
if let id = data["id"] as? Int {
    print("id: \(id)")
}

// Safely unwrap "message" parameter (String)
if let message = data["message"] as? String {
    print("message: \(message)")
}
// Safely extract payload data (nil if missing)
NSNumber* idValue = [data objectForKey:@"id"];
NSString* messageValue = [data objectForKey:@"message"];

if (idValue != nil) {
    NSLog(@"id: %@", idValue);
}

if (messageValue != nil) {
    NSLog(@"message: %@", messageValue);
}

Note: Unlike GCM / FCM, we do not stringify your payload data, except if you supply JSON objects or arrays.