SimpleSample-messages users-ios

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



Project homepage on GIT —

Download ZIP -


This sample demonstrates how to work with QuickBlox 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 Push Notifications API

Getting a QuickBlox account

Creating applications in the Admin panel

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 Push Notifications 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 -> Push Notifications -> type your message in Simple mode -> and hit "Send" for all of your users to receive the message; 2) Send a push using Push Notifications 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 code sample 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:


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


    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:92];
    [QBSettings setAuthKey:@"wJHdOcQSxXQGWx5"];
    [QBSettings setAuthSecret:@"BTFsj7Rtt27DAmT"];
    [QBSettings setAccountKey:@"7yvNe17TnjNUqDoPwfqp"];

    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 Push Notifications 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 ViewController.m and update it with login & password of the User you have manually created via admin panel previously:
    __weak typeof(self) weakSelf = self;
    [QBRequest logInWithUserLogin:@"qbpushios" password:@"qbpushios" successBlock:^(QBResponse *response, QBUUser *user) {
        [weakSelf registerForRemoteNotifications];           
    } errorBlock:^(QBResponse *response) {
    - (void)registerForRemoteNotifications{
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
            [[UIApplication sharedApplication] registerForRemoteNotifications];
            [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
  4. Subscribe User to receive Push Notifications
    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
        NSString *deviceIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        QBMSubscription *subscription = [QBMSubscription subscription];
        subscription.notificationChannel = QBMNotificationChannelAPNS;
        subscription.deviceUDID = deviceIdentifier;
        subscription.deviceToken = deviceToken;
        [QBRequest createSubscription:subscription successBlock:^(QBResponse *response, NSArray *objects) {
        } errorBlock:^(QBResponse *response) {

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).

Removing a user's Push Notification subscription

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

NSString *deviceUdid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
[QBRequest unregisterSubscriptionForUniqueDeviceIdentifier:deviceUdid successBlock:^(QBResponse *response) {
    // Unsubscribed successfully
} errorBlock:^(QBError *error) {
    // Handle error

Sending Push Notifications

Send Push Notifications from the Admin panel

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


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


and on the end of the user:


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

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


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


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 *pushMessage = [[QBMPushMessage alloc] initWithPayload:payload];
// Send push to users with ids 292,300,1395
[QBRequest sendPush:pushMessage toUsers:@"292,300,1395" successBlock:^(QBResponse *response, QBMEvent *event) {
    // Successful response with event
} errorBlock:^(QBError *error) {
    // Handle error

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'
[QBRequest sendPush:pushMessage toUsersWithAnyOfTheseTags:@"man,car" successBlock:^(QBResponse *response, QBMEvent *event) {
    // Successful response with event
} errorBlock:^(QBError *error) {
    // Handler error
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

With custom parameters

Please refer to Universal Push Notifications payload format to get more details what parameters you can use and also how you can initiate iOS VoIP push notifications (you can initiate VoIP push by passing ios_voip=1 parameter).

// Send push to users with ids 292,300,1295
NSDictionary *payload = @{
                          @"message" : @"Message received from Bob",
                          @"ios_badge" : @"5",
                          @"ios_sound" : @"mysound.wav",
                          // custom params
                          @"user_id" : @"133994123",
                          @"thread_id" : @"10"};
NSData *data =
[NSJSONSerialization dataWithJSONObject:payload
NSString *message =
[[NSString alloc] initWithData:data
QBMEvent *event = [QBMEvent event];
event.notificationType = QBMNotificationTypePush;
event.usersIDs = @"292,300,1295";
event.type = QBMEventTypeOneShot;
event.message = message;
[QBRequest createEvent:event successBlock:^(QBResponse *response, NSArray<QBMEvent *> *events) {
    // Successful response with event
} errorBlock:^(QBResponse *response) {
    // Handle error

Send universal voip push to users with ids 292,300,1295

QBMEvent *event = [QBMEvent event];
event.usersIDs = @"292,300,1295";
event.type = QBMEventTypeOneShot;
NSDictionary *paloadDictioary = @{@"user_id" : @"23941239",
                                  @"thread_id" : @"10",
                                  @"ios_voip" : @"1"};
NSData *sendData =
[NSJSONSerialization dataWithJSONObject:paloadDictioary
NSString *jsonString =
[[NSString alloc] initWithData:sendData
event.message = jsonString;
[QBRequest createEvent:event
          successBlock:^(QBResponse *response, NSArray<QBMEvent *> *events)
     // Successful response with event
 } errorBlock:^(QBResponse * _Nonnull response) {
     // Handle error

Simple push with text
// Send push to users with ids 292,300,1295
[QBRequest sendPushWithText:@"Hello world" toUsers:@"292,300,1295" successBlock:^(QBResponse *response, QBMEvent *event) {
    // Successful response with event    
} errorBlock:^(QBError *error) {
    // Handle error

Adding support for VOIP push notifications

From SDK 2.9.2 you can use VOIP push notifications.

Sending VOIP push notification with custom payload

QBMPushMessage *pushMessage = [[QBMPushMessage alloc] initWithPayload:@{
    @"text" : @"Hello World !"
NSString *userID = [NSString stringWithFormat:@"%tu", self.user.ID];
[QBRequest sendVoipPush:pushMessage toUsers:userID
    successBlock:^(QBResponse * _Nonnull response, QBMEvent * _Nonnull event) {
    } errorBlock:^(QBError * _Nonnull error) {

Receiving VOIP push notification

Example below shows how to receive and read VOIP push notification using Apple's new PushKit.

First setup push registry and subscribe for remote notifications (don't forget to create Quickblox subscription). pushRegistry property is an instance of PKPushRegistry class. And your current class should conform to PKPushRegistryDelegate protocol.

    self.pushRegistry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
    self.pushRegistry.delegate = self;
    self.pushRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
    UIUserNotificationSettings* notificationSettings =
    [UIUserNotificationSettings settingsForTypes:
     UIUserNotificationTypeAlert | UIUserNotificationTypeBadge |
     UIUserNotificationTypeSound categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];

Next just add appropriate delegates and handle received notifications in your own way.

- (void)pushRegistry:(PKPushRegistry *)registry
didUpdatePushCredentials:(PKPushCredentials *)credentials
             forType:(NSString *)type {
    NSString *str = [NSString stringWithFormat:@"didUpdatePushCredentials: %@", credentials.token];
    NSLog(@"%@", str);
    NSString *deviceIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    QBMSubscription *subscription = [QBMSubscription subscription];
    subscription.notificationChannel = QBMNotificationChannelAPNSVOIP;
    subscription.deviceUDID = deviceIdentifier;
    subscription.deviceToken = [registry pushTokenForType:PKPushTypeVoIP];
    [QBRequest createSubscription:subscription successBlock:^(QBResponse *response, NSArray *objects) {
    } errorBlock:^(QBResponse *response) {
- (void)pushRegistry:(PKPushRegistry *)registry
didInvalidatePushTokenForType:(NSString *)type {
    NSString *str = [NSString stringWithFormat:@"didInvalidatePushTokenForType: %@", type];
    NSLog(@"%@", str);
- (void)pushRegistry:(PKPushRegistry *)registry
didReceiveIncomingPushWithPayload:(PKPushPayload *)payload
             forType:(NSString *)type {
    NSString *str = [NSString stringWithFormat:@"didReceiveIncomingPushWithPayload: %@", payload.dictionaryPayload];
    NSLog(@"%@", str);

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:


Connecting Rich Content to push notifications

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


Next, check your uploaded image and press Add Selected button


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


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
    [QBRequest TDownloadFileWithBlobID:[richContent intValue] successBlock:^(QBResponse *response, NSData *fileData) {
        imageView.image = [UIImage imageWithData:fileData];
    } statusBlock:nil errorBlock:nil];}

You will see something like this: