Tuesday, 25 February 2014

iPhone Development:Push notification in Iphone SDK and Add custom sound to Push Notification




Push Notification IOS
Tags: #PushNotification #Tutorial #IOS8 

Push notification is a great feature that gave app developer/owner a chance to remind their app user's that something new happened to the app.
Mostly push notification is used in the apps that heavily depends upon remote server and required to have attention of their user's. e.g. like a store app, if a new offer is going to be started in a store then app should notify their user's about the offer so that they can grab it instantly.
We can add push notification to our iPhone App using a small chunk of code.


First you have to register for push Notification by using registerForRemoteNotificationTypes method of UIApplication class.You can write this in didFinishLaunchingWithOptions  method of your AppDelgate class.

Update: With IOS 8 you can register for push notification using the below code

IOS 8 onwards code:

if ([[[UIDevice currentDevice]systemVersion]floatValue]>=8.0)
    {
        if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
        {
            [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
            [application registerForRemoteNotifications];
        }

    }

IOS 7 and below code:

[[UIApplication sharedApplication]registerForRemoteNotificationTypes:
UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|
UIRemoteNotificationTypeSound];


As soon as this line of code hits it will call its didRegisterForRemoteNotificationsWithDeviceToken delegate method that will give us device token.Below is the chunk of code that tells you how to obtain a device token. I used NSUserDefault to save device token so that i can use it further.

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *deviceTockenString = [[NSString alloc]initWithString:[[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]];
    deviceTockenString = [deviceTockenString stringByReplacingOccurrencesOfString:@" " withString:@""];
    //NSLog(@"device string == %@",deviceTockenString);
    NSUserDefaults *loginSessionCredentials = [NSUserDefaults standardUserDefaults];
    [loginSessionCredentials setValue:deviceTockenString  forKey:@"devicetoken"];
    [loginSessionCredentials synchronize];
  }

NOTE:- This method only triggers if your provision profile has push notification enabled.You can change it by logging into developer.apple.com. Also push notification did not work on simulators.

If your app fails to register then your didFailToRegisterForRemoteNotificationsWithError  delegate will be called

(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    [AppDelegate showAlertWithTittle:@"Error!" andMessage:@"Error registering for push notification."];
    NSUserDefaults *loginSessionCredentials = [NSUserDefaults standardUserDefaults];
    [loginSessionCredentials setValue:@"No tocken"  forKey:@"devicetoken"];
    [loginSessionCredentials synchronize];

}
+(void)showAlertWithTittle:(NSString *)tittleString andMessage:(NSString *)messageString
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:tittleString message:messageString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
    [alert show];[alert release];
}


Test your app now. If you receive an alert that ask for push notification permission on app start-up, then its fine otherwise there's something wrong. Please follow above steps carefully.

Now you have to create Apple push development certificate and with the help of it you have to generate .pem file, this file is very important as we place this file on our  server so that our server can communicate with Apple Push server. You can create .pem file using steps mentioned in given this http://stackoverflow.com/questions/1481443/apple-push-notification-service

If you succeed then you have to implement didReceiveRemoteNotification delegate that will be gets called when you receive push notification from your server.

(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    //NSLog(@"userinfo == %@",userInfo);
      if (application.applicationState == UIApplicationStateActive ) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Notification" message:[[userInfo valueForKey:@"aps"]  valueForKey:@"alert"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}


Now ask your server guy to send a push to your device token.If your app is in foreground then their will be an alert pops up.If its in background or not running then a banner will be displayed on top of your home screen with sound and a badge on your app icon.
You  have to set it to zero when your app become active so that all notifications from notification center gets cleaned up.You can do it by writing below line of code

[[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];

If you want to maintain a badge count for per device then, you have to maintain it on the server and had to reset it to zero whenever an app opened up.
If you are not seeing any badge on app icon when you got your push then you had to cross check with serve guy whether he is sending badge key in payload or not.Your payload should be as given below

{
    "aps": {
        "badge": 10,
        "alert": "Hello",
        "sound": "sound.wav" or "yes" in case you want to use default sound.
    }
}

For custom sounds you have to add sound files in your app bundle, but you can use only three types of sounds as per Apple Inc. Documentation and these are wav, aiff or caf file and gave the sound file name in sound key of your payload.Also make sure that these sound files were added as a nonlocalized resource of the application bundle.

NOTE:- If you are showing a different view when the user came to your app by tapping on notification in notification center  then you have to check thdidFinishLaunchingWithOptionsis in method of AppDelgate.You can do this by writing below line of code
NSDictionary * notifDictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];    if (notifDictionary)
    {
       // [self application:application didReceiveRemoteNotification:notifDictionary];
    }







No comments:
Write comments