PushNotification Class

PushNotification is used to configure push notifications and send them from an Apex trigger.

Namespace

Messaging

Example

This sample Apex trigger sends push notifications to the external client app named Test_App, which corresponds to a mobile app on iOS mobile clients. The trigger fires after cases have been updated and sends the push notification to two users: the case owner and the user who last modified the case.

1trigger caseAlert on Case (after update) {    
2    
3    for(Case cs : Trigger.New)  
4    {
5        // Instantiating a notification
6        Messaging.PushNotification msg = 
7            new Messaging.PushNotification();
8
9        // Assembling the necessary payload parameters for Apple.
10        // Apple params are: 
11        // (<alert text>,<alert sound>,<badge count>,
12        // <free-form data>)
13        // This example doesn't use badge count or free-form data.
14        // The number of notifications that haven't been acted
15        // upon by the intended recipient is best calculated
16        // at the time of the push. This timing helps
17        // ensure accuracy across multiple target devices.
18        Map<String, Object> payload = 
19            Messaging.PushNotificationPayload.apple(
20                'Case ' + cs.CaseNumber + ' status changed to: ' 
21                + cs.Status, '', null, null);
22
23        // Adding the assembled payload to the notification
24        msg.setPayload(payload);
25
26        // Getting recipient users
27        String userId1 = cs.OwnerId;
28        String userId2 = cs.LastModifiedById;
29
30        // Adding recipient users to list
31        Set<String> users = new Set<String>();
32        users.add(userId1);
33        users.add(userId2);                       
34
35        // Sending the notification to the specified app and users.
36        // Here we specify the API name of the external client app.  
37        msg.send('Test_App', users);
38    }
39}