Monday 4 April 2011

Apple Push Notifications Steps

Creating an App ID  -

First of all  iPhone application that uses the APNs must have a unique application ID  to uniquely identify itself.

So first we will create an App ID for push notification.

1. Open http://developer.apple.com/ and Log in  with your apple developer id. Select iOS provisioning portal.

 

2. Select App IDs from left side.

3. Select New App ID button.

4. Fill it with your app details.

Note : For push notification Bundle Identifier (App ID Suffix) must not contain "*" .  An App ID without .* means its unique and works only for a single application.

5. Now you should be able to see your newly created App Id in the app IDs page. 

Configure App ID for Push Notification -


6. To configure App ID click on Configure in the app IDs page.
  
Note : You should only see Configure Link when you are logged in with Team Agent Account.


7. Here you will see option to enable Push Notification service.Click on it to enable push notification.


8. For configuring your Development and Production SSL Certificate you need to create a Certificate     Request File.

Generating a Certificate Request -

9. Open Key-chain in MAC.

10. GO TO Key-chain Access->Certificate Assistant->Request a Certificate from certificate Authority



11. Enter Email Address and your Name.



12. Select "Saved to Disc" and Continue to save the Certificate on your PC.



13. Now  Click on Configure Button displayed to the right of the App ID. I am choosing Development SSL certificate first.


14. Next there will be  Apple Push Notification service SSL Certificate Assistant screen.Click Continue.






15. Click  Choose File button to locate the Certificate Request file that you have saved earlier(Steps 10,11,12) 






16. Save your generated SSL Development Certificate.






Note : Repeat steps(13,14,15,16) to generate Production SSL Certificate as well.


17. The SSL Certificate's that you downloaded will be 
a. aps_developer_identity.cer.
b.   aps_production_identity.cer


18. Now you will be having a green light besides your SSL certificate status with an expiry date means on this date your push notifications will stop.Then you have to renew them.




19. Double-click on them to install it in the Keychain Access application






19.Now you have to export these new certificate and the private key of this certificte  and saved as .p12 files.




20. You will be asked  to provide export password.Give a password to export.It will be needed when you convert them in (.pem) format.






21.   Type these commands to generate the cert and key in Mac’s Terminal for PEM format (Privacy Enhanced Mail Security Certificate)


            openssl pkcs12 -clcerts -nokeys -out certdev.pem -in certdev.p12
            openssl pkcs12 -nocerts -out keydev.pem -in keydev.p12



22. If you want to remove the passphase of private key in key.pem


            openssl rsa -in keydev.pem -out keydev.unencrypted.pem


23. Combine the certificate and key


             cat certdev.pem keydev.unencrypted.pem > cerdev.pem


Note: Set the file permission of this keydev.unencrypted.pem key by using chmod 400 and is only readable by root ..


24. Following is a sample php script i foud on NET and modify it according to my parameters.if you put this php script and " cerdev.pem " and " cerpro.pem " in MAC local web server, you can use this to test

http://127.0.0.1/~rishi/apns.php?server=development&message=rishi&badge=10&mytune.caf&token=0ede6e28513f23725c05ba03fb79700........

http://127.0.0.1/~rishi/apns.php?server=production&message=rishi&badge=10&mytune.caf&token=09rf56g6fslj439fgdsfg00wef3........

Note: Device token is different in distribution and release build because of different certificates.


apns.php

<?php
   $deviceToken = $_GET['token'] or $deviceToken = $argv[2] ;//or $deviceToken reason
   // Passphrase for the private key (ck.pem file)
   // $pass = '';
   // Get the parameters from http get or from command line

  
   $message = $_GET['message'] or $message = $argv[3] or $message = 'You have a new mail';
   $badge = (int)$_GET['badge'] or $badge = (int)$argv[4]  ;
   $sound = $_GET['sound'] or $sound = $argv[5];
   // Construct the notification payload
   $body = array();
   $body['aps'] = array('alert' => $message);

   if ($badge)
      $body['aps']['badge'] = $badge;
   if ($sound)
      $body['aps']['sound'] = $sound;

   /* End of Configurable Items */
   $server = $_GET['server'] or $server = $argv[1] or $server = 'developement';
   echo $server;
   if($server=='production')
   {
           $appleServer='ssl://gateway.push.apple.com:2195';
          $certpem = dirname(__FILE__).'/cerpro.pem';
          echo "production set";
   }
   else
   {
  
           $appleServer='ssl://gateway.sandbox.push.apple.com:2195';
          $certpem = dirname(__FILE__).'/cerdev.pem';
   }
    $ctx = stream_context_create();
   stream_context_set_option($ctx, 'ssl', 'local_cert', $certpem);
   // assume the private key passphase was removed.
   // stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
   $fp = stream_socket_client($appleServer, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
   if (!$fp) {
      print "Failed to connect $err $errstrn";
      return;
   }
   else {
       print "Connection OK";
   }
    $payload = json_encode($body);
   $msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
  print "sending message :" . $payload . "n";
//    print "sending message :" . $msg;
   fwrite($fp, $msg);
   fclose($fp);
?>

25. Open your xcode project add the following code to get device token

- (void)applicationDidFinishLaunching:(UIApplication)application 
   //Register for Notifications
   [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
       
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
{
    NSString *str = [NSString stringWithFormat:@"%@", deviceToken];
NSLog(str);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{     
      NSString *str = [NSString stringWithFormat:@"Error %@", err];
NSLog(str);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{
    //
}


26. Once you run this script with the following hard coded parameters you will get push notification on the device whose device token you provide in last parameter of script.





Thursday 24 March 2011

Conversions in objective C

 These are some conversions which an objective C developer often needs while writing code.

NSString to Char * -
NSString *testString = @"Testing"; 
char *testCharP; 
testCharP = (char*)[testString cStringUsingEncoding:NSUTF8StringEncoding];
Char * to NSString -
const char *testCharP = "Testing"; 
NSString *testString;
testString = [NSString stringWithUTF8String:testCharP]; 
NSData to NSString -
NSString* Str = [[NSString alloc] initWithData:tempData
                                         encoding:NSUTF8StringEncoding];
if data is NULL terminated - 
NSString* Str = [NSString stringWithUTF8String:[tempData bytes]];



 

Monday 14 March 2011

Xcode shortcuts

Comment Code -
-------------------------
Alt + /      or    Command + /

Switch Between .h & .m
-------------------------------
Command+Windows+Up-Arrow   or   Command+Option+Up-Arrow

Short API Documentation -
----------------------------------
Windows+Double-click or Command+Double-click

BookMark -
--------------
Alt+D or Control+D 

Go TO Bookmark -
------------------------
Alt+4 or Control+4

Zoom Editor-
----------------
Alt+Shift+E or Command+Shift+E

Indentation of Code -
---------------------------
Alt+] (Right) or Command+]
Alt+[ (Left)   or Command+[

Key bindings in Xcode -
-------------------------------
From the Xcode menu choose Preferences
Go to Tab Key Bindings
Check key Bindings Sets:"Xcode Default"
Create a Duplicate of all the default setting by clicking Duplicate button in case you have to revert it.
Click on  Actions in the list you want to change.

Enter the new key combination you want.
Click Ok to save your changes
Open Console -
-------------------
Alt+Shift+R or Command+Shift+R

Open Debugger-
-------------------
Alt+Shift+Y or Command+Shift+Y

Build Results -
-------------------
Alt+Shift+B


Jump to a Line -
----------------------
Alt + L



Wednesday 2 March 2011

Removing invisible breakpoints in xcode debugger

There are times when your debugger stuck at invisible breakpoints.To solve this issue just run the application and open the console of xcode , wait for the breakpoint to hit.Then enter the following command in console after "[gdb]" prompt.
  • clear

You will get confirmation like this "Deleted breakpoint 8" where 8 is the number of breakpoint deleted.
You can see your all breakpoints by this command
  • info breakpoints

Tuesday 1 March 2011

How to open and block ports in mac

This is my first post.
These commands are useful when you work on  your i-phone project in simulator for checking connection issues like blocking  a port in mac to check how you application will behave if network is unavailable to your app.

For blocking a port -
sudo ipfw add 9060 deny dst-port 5060 via en0

where 5060 is the port and 9060 is the id.

For unblocking a port -
 sudo ipfw del 9060

 where 9060 is the id you used to block port 5060.