Documentation : Push notifications - iOS

This example shows how to send push notifications to all users or just to one specified user.

Push notifications on iOS devices are provided by Apple Push Notification Service (APNs). Basic knowledge of it's mechanisms are necessary to complete this tutorial. 

Main screen of an application contains three buttons, one for sending push notifications to all users and two for sending push notification to specified users. When application recieve notifications, toast message will be shown. There are two users in the system and there's a possibility to switch user on application life time.

Design Your App

First of all, log in to iOS Dev Center and move to the iOS Provisioning Portal. Next, go to App Id's section and follow instructions to create Push SSL Certificate for Development. Now we will move to Mobeelizer App Designer. Create application called PushNotifications.

Because there are no models in application we can move to push notification section. There we enable push notifications. Now edit push notifications for iOS devices in test environment. Next we have to upload certificate and provide password.

When everything is done in Create mode, deploy our application to test environment, and create two users with passwords:

  • a - usera
  • b - userb

Finally, download configured template for iOS project. Change class prefix to MD and model prefix to MMD.

Use the Mobeelizer SDK

Open project in XCode. We can see that several files has been generated and configured.  

Configure AppDelegate

First of all, there is app delegate with configured creation and destruction of Mobeelizer object. We should also register for remote notifications. Generated application does not have any view. We will add storyboard: MDStoryboad to our application and set newly created storyboard as Main Storyboard in project settings. Furthermore, we have to remove setting new window from application: didFinishLaunchingWithOptions: in MDAppDelegate

MDAppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Initialize Mobeelizer SDK
    [Mobeelizer create];
	[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert];
 
    return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application
{   
    // Terminate Mobeelizer SDK
    [Mobeelizer destroy];
}

When registering for remote notifications on iOS platform we should implement several functions. When we obtain token from APNS (Apple Push Notification Service), we have to pass this token to Mobeelizer. Moreover, when we recieve remote notification, we will display alert with message content. 

MDAppDelegate.m
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token {
    //Register to Mobeelizer remote notifications
	MobeelizerOperationError *error = [Mobeelizer registerForRemoteNotificationsWithDeviceToken:token];
    if(error != nil) {
        NSLog(@"Register for remote notification failure: %@ - %@", error.code, error.message);
    }
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSLog(@"Error in registration. Error: %@", err);
}

- (void)application:(UIApplication *)app didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"MESSAGE RECEIVED: %@", userInfo);
    NSString* messageContent = userInfo[@"aps"][@"alert"];
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Push received!"
                                                message:messageContent
                                                delegate:nil
                                            	cancelButtonTitle:@"OK"
                                            	otherButtonTitles:nil];
    [message show];
}

MDAppDelegate.m

Both application.xml and Mobeelizer.plist were generated. In Mobeelizer.plist we have to change mode from development to production

Create user login and logout manager

Next, we will handle user functionality. We will create singleton class MDUserManager, which will hold information about currently logged user. There are two use cases to handle user functionality. Firstly, when application starts user a will be logged in. Secondly, during runtime, users can be switched.

MDUserManager.h
@property (copy, nonatomic) NSString* user;
 
+ (SSUserManager*)instance;
- (BOOL) performLoginAsUser:(NSString *)login;
- (void) switchUser;
MDUserManager.m
- (BOOL) performLoginAsUser:(NSString *)login{
    self.user = login;
    NSString* password = nil;
    if ([login isEqualToString:USER_A]) {
        password = @"usera";
    } else {
        password = @"userb";
    }
 	//Login to Mobeelizer instance
    MobeelizerOperationError *error = [Mobeelizer loginToInstance:@"test" withUser:login andPassword:password];
 
    if(error != nil) {
        NSLog(@"Joining failed: %@ - %@", error.code, error.message);
    }
    return error == nil;
}
 
-(void) switchUser{
    if ([self.user isEqualToString:USER_A]) {
        self.user = USER_B;
    } else {
        self.user = USER_A;
    }
 
    [self performLogout];
    [self performLoginAsUser:self.user];
}
 
- (void) performLogout {
	//Logout from Mobeelizer
    [Mobeelizer logout];
}

MDUserManager.h MDUserManager.m

Next, we will move to user interface. Add a new file to project. Choose the UITableViewController subclass template and name the class MDUserContextController. We will add button to navigation bar, which will handle switching users. Controller will hold reference to button, because we will change appearance of button to show currently logged user.

MDUserContextController.h
#define RGB(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
#define USER_A_COLOR RGB(255, 128, 0)
#define USER_B_COLOR RGB(0, 128, 0)
 
@property (strong, nonatomic) UIBarButtonItem *userButton;
MDUserContextController.m
- (void)viewDidLoad{
    [super viewDidLoad];
    [[self navigationController] setNavigationBarHidden:NO animated:NO];
    userButton = [[UIBarButtonItem alloc] initWithTitle:@"User" style:UIBarButtonItemStyleBordered target:self action:@selector(userButtonClicked:)];
    self.navigationItem.rightBarButtonItem = userButton;
 
    [[MDUserManager instance] performLoginAsUser:USER_A];
}

Now add function to handle button click:

MDUserContextController.m
- (IBAction)userButtonClicked:(id)sender {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[MDUserManager instance] switchUser];
 
        dispatch_async(dispatch_get_main_queue(), ^{
            [self refreshUserButton];
 
            [UIView beginAnimations:@"View Flip" context:nil];
            [UIView setAnimationDuration:0.75];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
            [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
            [self reloadData];
            [UIView commitAnimations];
        });
    });
}
 
- (void)refreshUserButton {
    if ([[MDUserManager instance].user isEqualToString:USER_B]) {
        [userButton setTitle:@"B"];
        [userButton setTintColor:USER_B_COLOR];
    } else {
        [userButton setTitle:@"A"];
        [userButton setTintColor:USER_A_COLOR];
    }
}

MDUserContextController.h MDUserContextController.m

Currently, if any controller extends MDUserContextController, it will have functionality of switching users.

Create table view controller

Now, we will create view. Add navigation controller with table view controller to storyboard. Select table view and in Attribute inspector change content from dynamic prototypes to static content. Next increase number of sections to 2 and set style to grouped. Now select first section, change its header to Send to everyone and set number of rows to 1. Choose cell in first section, set style to basic and change title to Send push notification. Afterwards, select second section, change its header to Send to user and set number of rows to 2. For both pick basic style and change title respectively to Send to user A and Send to user B. Next, add a new file to the project. Choose the MDUserContextController subclass template and name the class MDPushController. Connect newly created controller to its design in storyboard. We will implement only one method for table view - tableView:didSelectRowAtIndexPath:

MDPushController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MobeelizerOperationError *error = nil;
    if (indexPath.section == 0 && indexPath.row == 0) {
		//Send Mobeelizer notification to all users
        error = [Mobeelizer sendRemoteNotification:[self createNotificationMessageWithContent:@"iOS device greets all users!"]];
    } else if (indexPath.section == 1 && indexPath.row == 0) {
		//Send Mobeelizer notification to specified user
        error = [Mobeelizer sendRemoteNotification:[self createNotificationMessageWithContent:@"iOS device greets user A!"] toUsers: @[@"A"]];
    } else if (indexPath.section == 1 && indexPath.row == 1) {
		//Send Mobeelizer notification to specified user
        error = [Mobeelizer sendRemoteNotification:[self createNotificationMessageWithContent:@"iOS device greets user B!"] toUsers: @[@"B"]];
    }

    if(error != nil) {
        NSLog(@"Send remote notification failure: %@ - %@", error.code, error.message);
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(NSDictionary*) createNotificationMessageWithContent:(NSString*) content {
    NSMutableDictionary* message = [[NSMutableDictionary alloc] init];
    message[@"alert"] = content;
    return [NSDictionary dictionaryWithDictionary:message];
}

MDPushController.h MDPushController.m 

There are few files, which are necessary userA.pnguserB.png.

Conclusion

Great, push notification example is done, we can send push notifications to all users in the system or to specified users. We can also send push notifications between other devices, implement same example on Android or iOS platform and check it by yourself. 

Attachments:

MDAppDelegate.m (application/octet-stream)
MDPushController.h (application/octet-stream)
MDPushController.m (application/octet-stream)
PushNotifications.png (image/png)
EnablePush.png (image/png)
AddUser.png (image/png)
PushNotificationsTemplate.png (image/png)