SimpleSample-messages users-ios

Ask tech team
From QuickBlox Developers (API docs, code samples, SDK)
Jump to: navigation, search

Contents

Sources

Project homepage on GIT — https://github.com/QuickBlox/quickblox-ios-sdk/tree/master/sample-messages

Download ZIP - https://github.com/QuickBlox/quickblox-ios-sdk/archive/master.zip


Overview

This sample demonstrates how to work with QuickBlox Messages (Push Notifications) API.
It allows to send and receive push notifications.

It shows how to:

  1. Subscribe user to start receiving push notifications
  2. Send a push notification to a user
  3. Work with Rich Push




Guide: Getting Started with Messages API

Getting a QuickBlox account

http://admin.quickblox.com/register

Creating applications in the Admin panel

http://admin.quickblox.com/apps/new

For further reading there is also this 5 minute guide.

Connecting QuickBlox to your application

To get the information on how to connect to the QuickBlox.framework please refer to the IOS-how-to-connect-Quickblox-framework page.

Creating APNS certificates

Each iOS application that uses Apple Push Notifications must have APNS certificates uploaded via the Admin panel. To get the information on how to create APNS certificates and upload them to Admin panel, please, refer to the How to create APNS certificates page.

Note: You must use valid Provisioning Profiles for your Xcode project.

How QuickBlox Push Notifications work

In order to use QuickBlox Messages APIs you must Create a session & Sign In to QuickBlox OR just create a session with a User.

There are 2 ways that you can integrate Push Notifications into your app:

  1. Broadcasting the same message to all users. It's a simple method which can be used in informational apps that do not authenticate users and where same push notification messages are broadcasted to everybody. This way when you want to send a push message you may 1) simply go to Admin panel -> Messages -> type your message in Simple mode -> and hit "Send" for all of your users to receive the message; 2) Send a push using Messages API (explained below). Following this way you only need to create ONE QuickBlox User which will have all of your users' devices associated with it. Then simply send your pushes to that User.
  2. Send individual push alerts. This is when you want to individually send push notifications to a particular user or a group of users (for example notify users of a new chat message sent while they are offline or tell them about some deal/event happening in close proximity to their location). Following this way you need to have a QuickBlox User created for each of your app users. Note that there are easy ways to transparently create QB Users along with your existing users authentication system or have them sign up with Facebook/Twitter/OAuth (described in Users API reference) so your end users don't have to type any additional login credentials or know anything about QuickBlox.

Giving a user a Push Notification subscription

  1. Let's create a test User via Admin panel and subscribe them to receive Push Notifications. Go to the Users module on Admin panel & press the Add new user button:

    AddNewUser.png

    Fill at least the login & password fields and press the Add user button

    SaveNewUser.png

    Also you can create a new User through Users APIs

  2. Updating your app's credentials
    In Appdelegate.m under
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    you will find something like:

        [QBSettings setApplicationID:1111];
        [QBSettings setAuthorizationKey:@"zzzzzzzzzzzzzz"];
        [QBSettings setAuthorizationSecret:@"runsnowdenrun"];
        [QBSettings setAccountKey:@"runsnowdenrunkey"];

    Assuming you have: 1) created your own application in the QuickBlox admin panel; 2) followed the steps above to create the APNS certificate; 3) uploaded the certificate via Messages dashboard. You now need to replace the above with your own app credentials (find them by clicking on app name in the list on the QB admin panel home page).

  3. Create QB session with User credentials
    Find the following code in /ViewControllers/SplashViewController/SplashViewController.m and update it with login & password of the User you have manually created via admin panel previously:
    QBASessionCreationRequest *extendedAuthRequest =[QBASessionCreationRequest request];
    extendedAuthRequest.userLogin = @"login";
    extendedAuthRequest.userPassword = @"password";                    
     
    [QBAuth createSessionWithExtendedRequest:extendedAuthRequest delegate:self];
  4. Subscribe User to receive Push Notifications
    You will find the following code in SplashViewController.m as well. No need to update anything here - just note this bit subscribes your user to receive push notifications:
    #pragma mark -
    #pragma mark QBActionStatusDelegate
     
    // QuickBlox queries delegate
    - (void)completedWithResult:(Result *)result{
     
        if(result.success) {
            // Create session result
            if([result isKindOfClass:QBAAuthSessionCreationResult.class]){
                // You have successfully created the session
     
                // Subscribe Users to Push Notifications
                [QBMessages TRegisterSubscriptionWithDelegate:self];
     
                // Subscribe User to Push Notifications result
            }else if([result isKindOfClass:QBMRegisterSubscriptionTaskResult.class]){
                // Now you can receive Push Notifications!
            }
     
        }else{
            NSLog(@"errors=%@", result.errors);
        }
    }

After that you are ready to receive Push Notifications!
Remember push alerts don't work in simulator - build to the device.
When adding to your existing app you will need to close the app on your device to be able to see the push notification alert (alternatively check Xcode log or implement in-app handling of push notifications as also done in current code sample).
Note: You have to use the lines below when you upload your application to App Store or create an AdHoc build:

#ifndef DEBUG
    [QBSettings useProductionEnvironmentForPushNotifications:YES];
#endif

Removing a user's Push Notification subscription

You can also unsubscribe the user which stops them from receiving any further push notifications:

[QBMessages TUnregisterSubscriptionWithDelegate:self];
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
- (void)completedWithResult:(Result *)result{
    // Unsubscribe from receiving push notification result
    if(result.success && [result isKindOfClass:QBMUnregisterSubscriptionTaskResult.class]){        
        // You have successfully unsubscribed from receiving push notification
 
    }else{
        NSLog(@"errors=%@", result.errors);
    }
}

Sending Push Notifications

Send Push Notifications from the Admin panel

Just go to Messages module on Admin panel, choose Environment, Channel, type the message and press the Send message button:

SendPushNotifications.png

Your message will be delivered to all subscribed Users. You will see:

NotifySuccess.png

and on the end of the user:

Push.jpeg


Also you can set more options through Advanced mode like this:

  • Group of Users (using Tags) that will receive the message

    PushNotificationsTags.png

  • Delivery settings (delayed send, recurring, activity interval)

    PushNotificationsDeliverySettings.png


Send Push Notifications from application (via API)

It's possible to send 2 types of push notifications:

  1. Platform based Push Notifications
  2. Universal push notifications


Refer to the Push Notification Formats document to better understand what happens under hood.

Platform based Push Notifications

Send Platform based push notifications (APNS) (only works for iOS mobile and Safari desktop). Platform based push notification will be delivered to specified platform only - in our case it's iOS mobile and Safari desktop:


Send Push Notification to particular users (through their IDs)

NSString *message = @"Hello man!";
NSMutableDictionary *payload = [NSMutableDictionary dictionary];
NSMutableDictionary *aps = [NSMutableDictionary dictionary];
[aps setObject:@"default" forKey:QBMPushMessageSoundKey];
[aps setObject:message forKey:QBMPushMessageAlertKey];
[payload setObject:aps forKey:QBMPushMessageApsKey];
 
QBMPushMessage *message = [[QBMPushMessage alloc] initWithPayload:payload];
 
// Send push to users with ids 292,300,1295
[QBMessages TSendPush:message toUsers:@"292,300,1395" delegate:self];
 
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
- (void)completedWithResult:(Result *)result{
    // Send Push Notifications result
    if(result.success && [result isKindOfClass:QBMSendPushTaskResult.class]){       
        // You have successfully sent push notifications
 
    }else{
        NSLog(@"errors=%@", result.errors);
    }
}


Send push notification to a group of users (via Tags)

NSString *mesage = @"Hello man!";
NSMutableDictionary *payload = [NSMutableDictionary dictionary];
NSMutableDictionary *aps = [NSMutableDictionary dictionary];
[aps setObject:@"default" forKey:QBMPushMessageSoundKey];
[aps setObject:mesage forKey:QBMPushMessageAlertKey];
[payload setObject:aps forKey:QBMPushMessageApsKey];
 
QBMPushMessage *message = [[QBMPushMessage alloc] initWithPayload:payload];
 
// Send push to groups 'man' and 'car'
[QBMessages TSendPush:message toUsersWithAnyOfTheseTags:@"man,car" delegate:self];
 
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
- (void)completedWithResult:(Result *)result{
    // Send Push Notifications result
    if(result.success && [result isKindOfClass:QBMSendPushTaskResult.class]){       
        // You have successfully sent push notifications
 
    }else{
        NSLog(@"errors=%@", result.errors);
    }
}

Universal push notifications

Universal push notifications will be delivered to all possible platforms and devices for specified users. With universal push notifications there are 2 ways to send it:

  1. Just send a simple push with text only
  2. With custom parameters


Simple push with text:

// Send push to users with ids 292,300,1295
[QBMessages TSendPushWithText:@"Hello World" toUsers:@"292,300,1295" delegate:self];
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
- (void)completedWithResult:(Result *)result{
    // Send Push Notifications result
    if(result.success && [result isKindOfClass:QBMSendPushTaskResult.class]){       
        // You have successfully send push notifications
 
    }else{
        NSLog(@"errors=%@", result.errors);
    }
}


With custom parameters:

// Send push to users with ids 292,300,1295
QBMEvent *event = [QBMEvent event];
event.notificationType = QBMNotificationTypePush;
event.usersIDs = @"292,300,129";
event.isDevelopmentEnvironment = ![QBSettings isUseProductionEnvironmentForPushNotifications];
event.type = QBMEventTypeOneShot; 
//
// custom params
NSMutableDictionary  *dictPush=[NSMutableDictionary  dictionaryWithObjectsAndKeys:@"Message received from Bob", @"message", nil];
[dictPush setObject:@"5" forKey:@"ios_badge"];
[dictPush setObject:@"mysound.wav" forKey:@"ios_sound"];
[dictPush setObject:@"234" forKey:@"user_id"];
//
NSError *error = nil;
NSData *sendData = [NSJSONSerialization dataWithJSONObject:dictPush options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:sendData encoding:NSUTF8StringEncoding];
//
event.message = jsonString;
 
[QBMessages createEvent:event delegate:self];
 
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
- (void)completedWithResult:(Result *)result{
    // Send Push Notifications result
    if(result.success && [result isKindOfClass:QBMEventResult.class]){       
        // You have successfully send push notifications
 
    }else{
        NSLog(@"errors=%@", result.errors);
    }
}

Adding Rich Push Notifications to your application

Rich Push Notifications allow you to deliver some rich media content (images, video, HTML/CSS/Javascript) to your users. This works as a combination of QB Push Notifications and QB [Content] APIs.

Uploading Rich Content

First, you need to create your rich content within the app or simply upload a file manually through the Admin panel. Let's upload a picture.

Go to Content module page on Admin panel, сhoose any image on your hard disk and press Upload button:

UploadContentToAdmin.png

Connecting Rich Content to push notifications

While creating the push notification message body, press Add Content button

ConnectContentToPush.png

Next, check your uploaded image and press Add Selected button

AddSelected.png

The image will be connected to the Push Notifications. Finally, choose Environment, Channel, type your message body and press the Send message button.

SendRichPush.png

Congrats! Rich Push Notification will be delivered to your subscribed Users!

Retrieving Rich Content

As you might know, push notifications can not contain large amounts of data. So above we have just sent a push notification with a link to rich content embedded into it. Next, you need to retrieve this content from the server and display it to the user. Don't worry about this - it's easy because you use QuickBlox!

When your application is activated from a push notification or when a push notification is received while the app is running, the AppDelegate's application:didReceiveRemoteNotification: method is usually called. This method contains userInfo param which contains your push notification message body in it. So, let's extract the link and download the associated rich content:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
 
    // Get push message
    NSString *message = [[userInfo objectForKey:QBMPushMessageApsKey] objectForKey:QBMPushMessageAlertKey];
 
    // Get link to rich content
    NSString *richContent = [userInfo objectForKey:QBMPushMessageRichContentKey];
 
    // Download rich content
    [QBContent TDownloadFileWithBlobID:[richContent intValue] delegate:self];
}
 
#pragma mark -
#pragma mark QBActionStatusDelegate
 
// QuickBlox API queries delegate
-(void)completedWithResult:(Result*)result{
 
    // Download rich content result
    if(res.success && [result isKindOfClass:[QBCFileDownloadTaskResult class]]){
        QBCFileDownloadTaskResult *res = (QBCFileDownloadTaskResult *)result;
 
        // show image
        imageView.image = [UIImage imageWithData:res.file];
    }
}

You will see something like this:

Conclusion

Now you can play around QuickBlox Messages API, integrate simple and rich Push Notifications into your apps and build some interesting use cases combining this with Chat, Location and other modules from QuickBlox!

Comments

Feel free to comment on this page using the form below

blog comments powered by Disqus