现在的位置: 首页 > 综合 > 正文

Apple Push Notification Service Tutorial

2013年07月17日 ⁄ 综合 ⁄ 共 6457字 ⁄ 字号 评论关闭

[iPhone]Apple Push Notification Service Tutorial



http://ameyashetti.wordpress.com/2009/07/31/apple-push-notification-service-tutorial/

Apple Push Notification Service (APNS) an service user by apple to
notify application. The notification can be of various Text Alert with
or without sound, Baggage number update on icon etc.

Below are the steps to construct an simple application that receives notification form APNS.

The steps are for development testing on sandbox APNS service from Apple

Getting Ready with Certificate and key.

  1. Generate a certificate signing request from your Mac’s keychain
    and save to disk.(Steps same as creating certificate for development but
    don’t submit not).
    Pleas store this certificate in a safe location as it might be re-required to invoke APNS.
  2. Login into your development account and visit iPhone Developer Program Portal.
  3. Click App IDs on left. Create an new id without wild charter
    (com.mydomain.applicationName). This name will be used while setting up
    your application to be signed with development certificate. If you use
    wild character like ‘*’ the iPhone Developer Program Portal will not
    allow the App ID to be used for notification.
  4. After submitting the new App ID you will be guided to the list
    page. Click configure to edit setting. Check ‘Enable for Apple Push
    Notification service’ to enable APNS , and click Configure next to
    ‘Development Push SSL Certificate’.
  5. Upload your request certificate generated in step 1 and download
    the certificate (aps_developer_identity.cer) from the Program Portal
    .
    Double click on this certificate to save it your key chain. Export this
    key by clicking on this newly installed certificate. The exported key
    is saved as Certificate.p12 file on your system. Please store it other
    files uploaded or downloaded from portal program. This .p12 file is used
    in later steps for signing your Provider server.
  6. Click on Provisioning in left bar and create a new provisioning
    profile. Use the new created App Id and select the device you want to
    use for development. Download the new provisioning profile save with
    other files. Close XCode if open and drag drop new provisioning profile
    on your XCode in your Doc bar.Your ready with certificate and key.

Getting ready with the application

  • Create an simple view based application.
  • Paste these line of code in your application.

- (void)applicationDidFinishLaunching:(UIApplication *)app {

// other setup tasks here….

[window addSubview:viewController.view];

[self alertNotice:@"" withMSG:@"Initiating Remote Noticationss Are Active" cancleButtonTitle:@"Ok" otherButtonTitle:@""];

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


}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

//NSLog(@”devToken=%@”,deviceToken);

[self alertNotice:@"" withMSG:[NSString
stringWithFormat:@"devToken=%@",deviceToken] cancleButtonTitle:@”Ok”
otherButtonTitle:@”"];


}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {

NSLog(@”Error in registration. Error: %@”, err);

[self alertNotice:@"" withMSG:[NSString stringWithFormat:@"Error
in registration. Error: %@", err] cancleButtonTitle:@”Ok”
otherButtonTitle:@”"];


}

-(void)alertNotice:(NSString *)title withMSG:(NSString *)msg
cancleButtonTitle:(NSString *)cancleTitle otherButtonTitle:(NSString
*)otherTitle{


UIAlertView *alert;

if([otherTitle isEqualToString:@""])

alert = [[UIAlertView alloc] initWithTitle:title message:msg
delegate:self cancelButtonTitle:cancleTitle otherButtonTitles:nil,nil];


else

alert = [[UIAlertView alloc] initWithTitle:title message:msg
delegate:self cancelButtonTitle:cancleTitle
otherButtonTitles:otherTitle,nil];


[alert show];

[alert release];

}

  1. Please be careful with the error reporting part in the code as error tell a lot about the development state.
  2. Right click on the application in target in the left and click
    Get Info to configure the application. Click on property tab and paste
    your App ID in the identifier text-field.
  3. Click build tab, select debug and select your new provisioning profile.
  4. Click Device 3.0 and Build Go to distribute binary to your connected device.
  5. Starting the application it should first alert and message that
    it registering for notification. Followed by and alert the application
    is registering for notification allow or deny. Followed by an alert that
    displays the device token ID. Note this token as this will be used by
    your server code to communicate with your device. If the second message
    is error then either something has gone wrong with the certificate and
    your application cannot register your certificate start over again.

Getting ready with Notification service provider.

Download an stand alone MAC application (PushMeBaby
http://stefan.hafeneger.name/download/PushMeBabySource.zip
) to test. There are two modification in the application to get started.
Place an copy of the aps_developer_identity.p12 file in the application
folder. Import the file in the application by right clicking and Add
> Existing File.
Set the following in the application’s delegate file as shown below

self.deviceToken = @”XXXXX XXXXX XXXXX XXXXXX XXXXXX”;

//First your device id token.

self.payload = @”{/”aps/” : { /”alert/” : /”You got your
emails./”,/”badge/” : 9,/”sound/” : /”bingbong.aiff/”},/”acme1/” :
/”bar/”,/”acme2/” : 42}”;


//The pay load

self.certificate = [[NSBundle mainBundle] pathForResource:@”aps_developer_identity” ofType:@”cer”]; //The certificate file.

  • Don’t depend on the application’s text-field as it doesn’t work.
  • Start the application and you will get a message the application
    is trying to access your key , click ‘Allow’. Click Push in the
    application window. Wait for a 20 seconds and you should immediately get
    an notification on your iPhone / iTouch.

Getting ready with test code for actual provider sever (PHP).

  • For server on linux environment you will require different kind
    of certificate. Following are the steps to create it. Use MAC console to
    fire the following commands.

openssl pkcs12 -clcerts -nokeys -out cert.pem -in Certificate.p12

provide new password if asked.

openssl pkcs12 -nocerts -out key.pem -in Certificate.p12

provide new password if asked.

cat cert.pem key.unencrypted.pem > ck.pem

Create an PHP file provide.php

$message);

if ($badge)

$body['aps']['badge'] = $badge;

if ($sound)

$body['aps']['sound'] = $sound;

/* End of Configurable Items */

$ctx = stream_context_create();

stream_context_set_option($ctx, ’ssl’, ‘local_cert’, ‘ck.pem’);

// assume the private key passphase was removed.

// stream_context_set_option($ctx, ’ssl’, ‘passphrase’, $pass);

$fp = stream_socket_client(’ssl://gateway.sandbox.push.apple.com:2195′, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);

if (!$fp) {

print “Failed to connect $err $errstrn”;

return;

}

else {

print “Connection OKn”;

}

$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”;

fwrite($fp, $msg);

fclose($fp);

?>

Note :
Your PHP server must have json_encode support.

Run your file on linux console as ‘php provide.php’

For more information refer http://www.macoscoders.com/2009/05/17/iphone-apple-push-notification-service-apns/

抱歉!评论已关闭.