»
S
I
D
E
B
A
R
«
iPhone Apple Push Notification Service (APNS)
May 17th, 2009 by Anish Kumar

Apple’s has announced a push notification service for the iPhone that it’ll provide to all developers. It’ll maintain a persistent IP connection to the phone and let a 3rd party server ping Apple’s notification service in order to push out notifications to users device, which can be in the form of badges, sounds or custom textual alerts. According to Apple, the service will preserve battery life and maintain performance, not to mention work over WiFi or cellular.

What is Push Notification and How does it work?

Let’s say you’re running a 3rd party IM (instant message) client on iPhone 2.0. When you exit the app, you no longer know if you’re receiving more messages. (Sure, there are work around over SMS and Email, but the app itself is dead to you).

With Apple’s Push Notification Service on iPhone OS 3.0, anytime someone sends you a new IM, an alert can be sent from the IM  developer’s servers (yes, they’ll have to keep a session open for you on their end), to Apple’s Push Notification Service (APNS) servers.

Apple’s PNS server will have a persistent TCP/IP connection to your iPhone . Once Apple PNS gets the alert from the developer server, APNS will “PUSH” it out to your iPhone 3.0.

Apple PNS currently supports 3 kinds of alerts: badges with a number (like Mail uses to show you unread messages), custom sounds (like a beep or bell or anything already built into the app by the developer), or modal message boxes (like the kind that pop up to tell you your battery is at 20%).

Apple isn’t making any promises on up-time for the service, and any new service will have delays and downtime.

What APNS doesn’t solve, however, is the lack of good notifications on the iPhone, and applications that require multitasking for something other than notification (i.e. streaming internet radio apps).

Imagine if 10 apps try to push out 10 alerts at the same time, how will Apple manage those on your device? Will you have to “cancel” or “accept” 50 modal message dialogs, or be hit by a cacophony of 30 random sounds? We don’t know yet, but hopefully Apple will address this.

Generate APNS SSL Certificate

To get started with APNS we need to generate an certificate unique to each applications which will support APNS. We need to log into our iPhone developer portal with “Team Agent” access.  Only users with “Team Agent” access can do the below mentioned process. The iPhone developer portal with “Team Agent ” has a detailed steps to generate an APNS certificate. You should be able to see the screen shown below in the portal to start creating your APNS certificate. Follow the steps mentioned below:-

APNS Development Certificate

Fig 1: APNS Development Certificate

(1) You need to create an App ID without .* in the iPhone developer Portal. An App ID without .* means its unique and works only for a single application

(2) Generate a certificate signing request from your Mac’s keychain (You should be an Team Agent to have access to the wizard shown in Figure 1) as shown in figure 2 and save to disk

(3) Upload the CertificateSigningRequest.certSigningRequest to the Program Portal

(4) Wait for the generation of cert (about 1 min). Download the certificate (aps_developer_identity.cer) from the Program Portal

(5) Keep (or rename them if you want) these 2 files (steps 2 and 4) in a safe place. You might need the CertificateSigningRequest.certSigningRequest file to request a production cert in the future or renew it again.

(6) Suppose you have imported the aps_developer_identity.cer to the keychain. Then you have to export these new cert and the private key of this cert (not the public key) and saved as .p12 files.

(7) Then you use 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 cert.pem -in cert.p12
openssl pkcs12 -nocerts -out key.pem -in key.p12

(8) The cert.pem and key.pem files will be used by your own program communicating with APNS.

(9) If you want to remove the passphase of private key in key.pem, do this

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

Then combine the certificate and key

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

But please set the file permission of this unencrypted key by using chmod 400 and is only readable by root in a sever configuration.

(10) The testing APNS is at ssl://gateway.sandbox.push.apple.com:2195

Request Certificate From Keychain Access

Fig 2: Request Certificate From Keychain Access

(11) For the source codes to push payload message to the APNS, you can find them in the Developer Forum. This is the one that I used, for php. Run this (after obtaining the device token from the testing device and with iPhone Client program setup)
php -f apns.php "My Message" 2

or if you put this php script and the ck.pem in a local web server, you can use this to test
http://127.0.0.1/apns/apns.php?message=Hello%20from%20macoscoders&badge=2&sound=received5.caf

apns.php


<?php
$deviceToken = '02da851dXXXXXXXXb4f2b5bfXXXXXXXXce198270XXXXXXXX0d3dac72bc87cd60'; // masked for security 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[1] or $message = 'Message received from javacom';
$badge = (int)$_GET['badge'] or $badge = (int)$argv[2];
$sound = $_GET['sound'] or $sound = $argv[3];
// 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 */
$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);
?>

(12) For iPhone Client Program, you need to edit the bundle identifier to the App ID that you created and imported the new provisioning profile for that APP ID to the XCode and iPhone. Then implement the following methods in AppDelegate to Build & Go

AppDelegate.m


- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSLog(@"Registering Remote Notications");
// For beta 2
// [[UIApplication sharedApplication] registerForRemoteNotifications];
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)]; // For beta 3
// other codes here
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"%@",[[[launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"] objectForKey:@"aps"] objectForKey:@"alert"]);
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"deviceToken: %@", deviceToken);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Error in registration. Error: %@", error);
}

(13) Additional tips

- The feedback service is currently unavailable.
- Send your messages to gateway.sandbox.push.apple.com:2195 during the beta period.
- Devices must be set up as new iPhones in iTunes in order to generate device tokens. Restoring from backup is not currently supported.
-Make sure the audio file received5.caf is included in your application resource.

(13a) Registering an App ID for Apple Push Notification service

1. In the App ID section of the Program Portal, locate the App ID you wish to use with the Apple Push Notification service. Only App IDs with a specific bundle ID can be used with the APNs. You cannot use a “wild-card” application ID. You must see “Available” under the Apple Push Notification service column to register this App ID and configure a certificate for this App ID.

2. Click the ‘Configure’ link next to your desired App ID.

3. In the Configure App ID page, check the Enable Push Notification Services box and click the Configure button. Clicking this button launches the APNs Assistant, which guides you through the next series of steps that create your App ID specific Client SSL certificate.

4. Download the Client SSL certificate file to your download location. Navigate to that location and double-click the certificate file (which has an extension of cer) to install it in your keychain.

5. When you are finished, click Done in the APNS Assistant.

6. Double-clicking the file launches Keychain Access. Make sure you install the certificate in your login keychain on the computer you are using for provider development. The APNs SSL certificate should be installed on your notification server.

7. When you finish these steps you are returned to the Configure App ID page of the iPhone Dev Center portal. The certificate should be badged with a green circle and the label “Enabled”.

8. To complete the APNs set-up process, you will need to create a new provisioning profile containing your APNs-enabled App ID.

About Me: Anish:
Mac OS X software development is my bread winner with over 6 years of experience. Expertise in Color Management, TWAIN Scanner drivers on Mac OS X, Photoshop Filter and Import Plugin development on Mac OS X, iPhone. As an hobby I love to work on PHP, Flex, AIR, Photoshop. Check the 'About' page for more.

106 Responses  
iphonebuyer writes:
May 26th, 2009 at 7:31 pm

[...] Anish Kumar wrote an interesting post today onMacOSCoders » Blog Archive » biPhone/b Apple Push Notification b…/bHere’s a quick excerpt [...]

KrisBelucci writes:
June 2nd, 2009 at 7:01 pm

I really liked this post. Can I copy it to my site? Thank you in advance.

Dennet writes:
June 3rd, 2009 at 12:21 pm

Thanks for this enlightening information… I however keep getting the following errors… Any ideas what I may be doing wrong? I have place the ck.pem file in the same folder as the script. I am stuck at this stage :(

Warning: stream_socket_client() [function.stream-socket-client]: Unable to set local cert chain file `/Users/dennet/Sites/APNS/ck.pem’; Check that your cafile/capath settings include details of your certificate and its issuer in /Users/dennet/Sites/APNS/ssl.php on line 25

Warning: stream_socket_client() [function.stream-socket-client]: failed to create an SSL handle in /Users/dennet/Sites/APNS/ssl.php on line 25

Warning: stream_socket_client() [function.stream-socket-client]: Failed to enable crypto in /Users/dennet/Sites/APNS/ssl.php on line 25

Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error) in /Users/dennet/Sites/APNS/ssl.php on line 25
Failed to connect 0

    Andreea writes:
    July 22nd, 2009 at 3:14 pm

    You managed to get rid of warning and you connect? If yes, please tell me how.

      Anish Kumar writes:
      July 22nd, 2009 at 5:25 pm

      Yeah I was finally able to get rid of those warnings and connect and send notifications successfully. Just be 100% sure that you upload the certificate from the machine which will act as the provider server. And then make sure to install the certificate that you get from APNS SSL certificate Assistant.

      regards,
      -Anish

        Kamal Challa writes:
        September 25th, 2009 at 2:05 pm

        Hi

        Its really a great post

        but i got

        Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out) in /home/permeati/public_html/permeativetech/apns/apns.php on line 9
        Failed to connect

        is there any work arround

        Thanks in advance

          Anish Kumar writes:
          September 25th, 2009 at 3:37 pm

          There is some problem with your certificate. Make sure you have followed all the steps to create the certificate properly.

          All the best,
          -Anish

            Kamal Challa writes:
            September 26th, 2009 at 11:23 am

            problem is the port 2195 is not enabled , can i do using 2195 ?

            If not how can i set up the environment to work APNs on local mac machine

            Thanks in advance

    Tej writes:
    October 23rd, 2009 at 8:29 pm

    Hi ,
    I have getting below warnings after firing http://localhost/apns.php?message=test%20from%20javacom&badge=2&sound=received5.caf this command ..

    I have apns.php files and also both .pem certificates in my root folder of WAMP server (Provider server).

    Warnings :

    Warning: stream_socket_client() [function.stream-socket-client]: Unable to set local cert chain file `ck.pem’; Check that your cafile/capath settings include details of your certificate and its issuer in C:\wamp\www\apns.php on line 29

    Warning: stream_socket_client() [function.stream-socket-client]: failed to create an SSL handle in C:\wamp\www\apns.php on line 29

    Warning: stream_socket_client() [function.stream-socket-client]: Failed to enable crypto in C:\wamp\www\apns.php on line 29

    Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error) in C:\wamp\www\apns.php on line 29
    Failed to connect 0

    Please let me know solution if any one get faced above warning and solved it

    Thanks in advance.
    Tej

      Tej writes:
      November 2nd, 2009 at 7:42 pm

      Hi,
      For my above post , i have got solution to overcome this four different types of warning comming because i have not configure the SSL server . When i have configure ssl server and put those files in root folder it’s works very well for me..

      So conclusion – if you got above four types of warning then please confirm if you have already configure the SSL server or not?
      If not then first configure that.

AndrewBoldman writes:
June 5th, 2009 at 2:18 am

Hi, good post. I have been wondering about this issue,so thanks for posting.

Mike writes:
June 9th, 2009 at 7:25 am

Hey, great post, really well written. You should blog more about this.

Naina Gill writes:
June 9th, 2009 at 4:25 pm

hey…its been a popular post!!

Kelly Brown writes:
June 13th, 2009 at 5:27 am

I really like your post. Does it copyright protected?

JaneRadriges writes:
June 14th, 2009 at 5:29 am

Great post! I’ll subscribe right now wth my feedreader software!

KattyBlackyard writes:
June 15th, 2009 at 7:40 am

Hi, very nice post. I have been wonder’n bout this issue,so thanks for posting

Tim Courtney writes:
June 16th, 2009 at 8:32 pm

Anish,

Great writeup, thanks for sharing! As someone interested in implementing push notifications, you’ll appreciate the heads-up on a new service we’re launching called iLime. iLime will provide a scalable hosted web service, APIs, and a RESTful interface for iPhone app developers to send push notifications and deliver content bought through In App Purchase.

Here’s our release from last week: http://bit.ly/VUvPL
And our site: http://www.ilime.com

If you have any questions or comments, please don’t hesitate to reach out. You can also find us on Twitter at http://www.twitter.com/ilimebuzz.

Best regards,

Tim

Anish Kumar writes:
June 16th, 2009 at 8:41 pm

Thanks Tim. iLime service sounds exciting. I will keep it mind and might contact you to get further details.
-Anish

Bahar writes:
June 17th, 2009 at 10:07 am

Simply a great post.

I am in the process of adding push notification service to our existing apps. your post has gave me head start :)

Keep rockin!

PG writes:
June 18th, 2009 at 5:20 am

You specify in point 6 the following :
6) Suppose you have imported the aps_developer_identity.cer to the keychain. Then you have to export these new cert and the private key of this cert (not the public key) and saved as .p12 files.

I don’t have a private key under my push services certificate. The only private key I have is under the iphone developer cerificate. Is this normal ?

Tarun Sharma writes:
June 20th, 2009 at 7:14 pm

Hi all,

Can someone explain me what is the wild card App id (is it with xxxxxxxxxx.*) and how to get app id without wild card (which is the requirement of push notification services).

I am an not clear about apple id (with and without wild card) concept.

Thanks,
Tarun sharma

Anish Kumar writes:
July 2nd, 2009 at 10:31 pm

Tarun,
Wild card app id means an application id created on the iphone developer portal that ends with a ‘*’ like com.apple.* We generally use wild card’s when we want to use the same profile to develop multiple applications. So a provision profile created with a wild card can be used say appA, appB etc like com.apple.appA and com.apple.appB

But however applications that support APNS requires that it has new profile created on the developer portal. we can’t use a provision profile which has a * in the app id for applications supporting APNS.

Hope this clears your doubt.
-Anish

    Prasanna Gopinath writes:
    November 4th, 2009 at 5:11 am

    Hi Anish,

    We have an app in AppStore with a APPID with a wild character ‘*’. Now we are doing Push Notification that cant take this wild character and we also want to upgrade the old app the new one.

    What is your recommendation? We cant get a new APPID in which case we cant upgrade the old app to new app and we want to support push notification as well in the new app.

    Thanks
    –Prasanna

PeterMontee writes:
July 3rd, 2009 at 6:34 am

It is remarkable, this very valuable opinion

Tarun Sharma writes:
July 4th, 2009 at 5:24 pm

Thanks Anish. That was very helpful.

KonstantinMiller writes:
July 6th, 2009 at 11:44 pm

Hello, can you please post some more information on this topic? I would like to read more.

Anish Kumar writes:
July 6th, 2009 at 11:53 pm

What kind of more information are you looking at Miller?

CrisBetewsky writes:
July 7th, 2009 at 12:23 am

You know, I don’t read blogs. But yours is really worth beeing read.

Srini writes:
July 7th, 2009 at 11:16 pm

Hi all,
I am getting the following error and not getting the device token.
erorr:
Domain=NSCocoaErrorDomain Code=3000 UserInfo=0×213e80 “no valid ‘aps-environment’ entitlement string found for application”
Code sign Identity looks fine.. what else I need to check?

I am getting the below line from Additional tips:
Devices must be set up as new iPhones in iTunes in order to generate device tokens. Restoring from backup is not currently supported

How to set it for my iPhone?

Thanks in Advance..

-Srini

Anish Kumar writes:
July 7th, 2009 at 11:40 pm

Hi Srini,
There is another post in my blog which talks about “no valid ‘aps-environment’”..but that doesnt seem to be the cause of your problem.
http://www.macoscoders.com/2009/06/23/error-no-valid-aps-environment-entitlement-string-found-for-application/

The additional tips seems to suggest you might have to install 3.0 on your iphone afresh and dont restore it after you install 3.0. iPhone’s had to be setup as new devices without restore from backup, for APNS to work in the beta period. However I didnt face this issue with my iPhone after the final iPhone OS 3.0 GM build was released. I have the APNS successfully working on my iPhone which has been restored from a earlier backup.

May be you should try reinstalling the iPhone OS 3.0 and make sure its not restored from backup.

Do let us know if that fixes your issue.

Happy Coding,
-Anish

    Srini writes:
    July 16th, 2009 at 5:08 pm

    Problem is with the provisioning profile created with the wildstar ‘*”. We created a new Provisioning profile for our application then it started working.

    Thanks All for your help…

    -Srini

yang writes:
July 8th, 2009 at 11:36 pm

Hi,

thanks for your help. I want to know if the push notification service can interrupt a call? I mean when I calling someone, I want the service to interrupt me through sent me message. I test this, it seems doesn’t work. but it works when i use other application.

Anish Kumar writes:
July 9th, 2009 at 5:48 pm

Hi Yang,
I tested sending push notification when my iPhone was on call and my iPhone failed to receive the notification. I didn’t get the notification even after the call was ended. This is not a desired behavior. Atleast Apple should send that notification after the call has ended. I will post any update on this issue later.

-Anish

    Yang writes:
    July 10th, 2009 at 11:03 pm

    Hi Anish,

    Thank you very much for your help. Hope can get a solution.

    -yang

Dhaval Dobariya writes:
July 20th, 2009 at 11:07 am

Hi all,

Can you please tell me,will apns.php work on the windows platform??
awaiting reply.

Thanks,
Dhaval

    Anish Kumar writes:
    July 20th, 2009 at 4:03 pm

    Hi Dhaval,

    You can use the apns.php on windows platform too. But then you need to have the certificates setup properly. I think setting it up correctly on windows is a pain. May be you might need to use the openssl too. Not tried though.

    -Anish

Venikom writes:
July 20th, 2009 at 3:58 pm

Hey is this ssl url steal working?

ssl://gateway.sandbox.push.apple.com:2195

becouse when we test to send push there is error – unable to conect to ssl server….

    Anish Kumar writes:
    July 20th, 2009 at 4:08 pm

    If you are getting unable to connect to ssl server, its highly that ur apns certificates as listed in the blog is not setup properly on your server. I used to get that error too and finally figured out that my certificates were not generated as it was required. I used certificates generated on my machine and placed it on a server running on a different machine. Make sure you follow the steps mentioned in the blog on the machine where server is running. This will fix that issue.
    -Anish

Srini writes:
July 22nd, 2009 at 5:08 pm

Hi,
Is it QOS Guaranteed in sandbox environment? Store and Forward?
I am trying to test some Push Notification behaviour with my iTouch Device and using
the Apple sandbox apn server.
I disabled Wi-Fi in my device. Try sending some notifications to the device from the provider. But I am not getting any notification even after enabling the Wi-Fi connection in my device.
As per the Apple Documenet , I should receive the last notification
sent by the Provider.

What is the behaviour when Provider sends notification to the device but the device is
switched off?

Qos in Sandbox APN Server handle the above cases? or Qos applicable only to
Production APN Server?

Thanks in Advance..

Regards,
Srini

    Anish Kumar writes:
    July 22nd, 2009 at 5:22 pm

    Hi Srini,

    I think Apple doesn’t guarantee any QOS atleast for the sandbox environment. According to documentation APNS is supposed to forward you the last notification sent by the provider. I have got notifications on my iPhone when it was connected to the internet after a while of sending the notification. But It worked only few times for me. Most times my device failed to get any notification. Prolly it might work better on a production APNS. May be if you try multiple times, it might work on sandbox. The conclusion is it does store and forward the notifications, but its not guaranteed on a sandbox environment.

    regards,
    -Anish

K-Fung writes:
July 31st, 2009 at 2:28 am

When I try to call apns.php in my local machine:php -f apns.php “My Message” 2
it works well.

However when I test from website:http://127.0.0.1/apns/apns.php?message=test%20from%20javacom&badge=2&sound=received5.caf

it show:
Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out) in /home1/xxx/public_html/apns.php on line 21
Failed to connect 110

The files: apns.php and ck.pem are the same, but one work and one failed.
Please help me.

K-Fung writes:
July 31st, 2009 at 2:43 am

Dear Anish,

I don’t understand about you said, “I used certificates generated on my machine and placed it on a server running on a different machine.”

I just follow your step and generated the ck.pem. After I tested it is working well on my mac mini, I tried to upload to my linux server, however it is not work:
Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out) in /home1/xxx/public_html/apns.php on line 21 Failed to connect 110

Please help me, million of thanks.

    Anish Kumar writes:
    August 2nd, 2009 at 12:40 am

    Dear Fung,

    What I meant when i said “I used certificates generated on my machine and placed it on a server running on a different machine.” was:- I created the certificates on my Macbook Pro and then uploaded them to a different machine running Mac OS X Server and as expected, the SSL connection failed.

K-Fung writes:
July 31st, 2009 at 2:54 am

Which file is the certificate I needed to upload to server?
And how to install the certificate, since the server is hosting on hostmonster?

Sorry for many question.

K-Fung writes:
July 31st, 2009 at 11:14 am

In hostmonster control panal, it is no method to upload the csr, but has a form to me, do you know how to fill in the blanks?

SSL Certificate Signing Request
If you are obtaining a certificate from a trusted SSL provider, you must complete the signing request form to provide the information needed to generate your SSL certificate.

Please note that your SSL provider may require your information in a specific way. Please check with their necessary CSR information for Apache.

Certificate Signing Requests on Server

Host Functions
There are no Certificate Signing Requests on the server

Generate a New Certificate Signing Request

Host
Country
State
City
Company
Company Division
Email
Pass Phrase

* You must generate or upload a key before you can generate any certificate signing requests.

K-Fung writes:
July 31st, 2009 at 12:17 pm

I have uploaded my Private Keys and Certificates (Apple Development Push Service) in CPANEL
but it does not work, I have no idea, would you please help me?

K-Fung writes:
August 1st, 2009 at 1:02 am

fixed

    Aravind writes:
    August 15th, 2009 at 9:22 pm

    Hi K-Fung,
    How exactly did you fix this issue? I am having the same trouble in hostmonster.

Anup George writes:
August 10th, 2009 at 2:58 pm

I am not able to retrieve the device token. What could be the possible areas that I might have missed.

Robert Simpson writes:
August 10th, 2009 at 7:31 pm

Hi, thanks for the great post.

I’m implementing a very similar php script which will process push notifications. What I’m worried about is the statement in Apple’s documentation which says that numerous attempts at connecting and disconnecting might be regarded as a denial-of-service attach. So, if I used the above script for every time I wanted to send a push notification would I create a new connection (and therefore create a problem). If so, how would I go about keeping the connection open say, for 5mins, and then close it if need be?

Thanks,

Rob

    Anish Kumar writes:
    August 12th, 2009 at 4:47 pm

    Hi Rob,

    You can perform the fwrite() operation in a loop before closing the connection to Apple APNS. Its not a good idea to open and close connections to send notification to individual devices.

    regards,
    -Anish

      Robert Simpson writes:
      August 12th, 2009 at 8:02 pm

      Thanks for the reply.

      Yes, this is what I plan to do in my implementation but my issue is that I want to send notifications very soon after I receive them (from another device) otherwise there will be a delay between receiving and sending. So I have looked around and I found a brief comment on a site saying that they set up a crontab with a queue system. So if I put all my push notifications in a database (forming a queue) and then ran the above php script every few seconds, would this constitute as connecting and disconnecting too often?

      Thanks!

pramod writes:
August 12th, 2009 at 4:26 pm

Hi,

I would like to know how to implement this php, for multiple users(device token).

Thank u.

    Anish Kumar writes:
    August 12th, 2009 at 4:51 pm

    Hi Pramod,

    I have implemented for multiple devices by performing the fwrite() operation in a loop. I store the device tokens of all my users in a db and then while sending notification, i loop through all the active devices to perform the write operation. Note I open and close the connection only once during the entire cycle. The looping code looks something like this:

    for($index=0; $index<=count($deviceTokens); $index++)
    {

    $deviceToken = $deviceTokens[$index];

    $payload = json_encode($body);
    $msg = chr(0) . pack(”n”,32) . pack(’H*’, str_replace(’ ‘, ”, $deviceToken)) . pack(”n”,strlen($payload)) . $payload;
    print “sending message :” . $msg . “\n”.”";
    $ret = fwrite($fp, $msg);

    echo “Return=”.$ret.”";
    }

    regards,
    -Anish

      pramod writes:
      August 12th, 2009 at 5:06 pm

      Hi Anish,

      Thanks for the quick reply.

      Solution just expected , but for confirmation support.
      I had one more doubt, whether the SSL Certificate should be generated on the Provider (server) PC or it can be generated on other system and then transferring the .pem file and installing it on the server would work.

        Anish Kumar writes:
        August 12th, 2009 at 5:12 pm

        Well you can’t simply move those .pem file created on a different machine directly to a server running on a someother machine. You will fail to connect to APNS server if you try to do that. However may be you can import the certificates probably using openssl tools? not sure of it though.
        -Anish

          pramod writes:
          August 12th, 2009 at 5:40 pm

          Hey then how would it be possible to install the .pem certificate on the Non MAC OS servers.

pramod writes:
August 12th, 2009 at 5:07 pm

Hi Anish,

One more thing I am having the Linux server.

Thanks

pramod writes:
August 12th, 2009 at 5:09 pm

Does APNS works on UNLOCKED and JAILBREAK phones.

    Anish Kumar writes:
    August 12th, 2009 at 5:10 pm

    I think it will work on unlocked and jailbroken phones too. I remember seeing it on my friends device.
    -Anish

pramod writes:
August 12th, 2009 at 7:32 pm

Hi,

I would like to know whether our AppId’s generated in iphone programme portal will be displayed in the AppIdS list at the portal.

To be clear, I had a situation when , I developed the Provisioning profile for my app using comm.companyname.appname. Then if I want to generate SSL Certificate for the app, will the AppIds will be available

Thank you.

ciri writes:
August 28th, 2009 at 9:04 pm

It seems to works fine, I don’t receive errors messages, but the notifications don’t arrive on my iPhone.

Where can to be the error?

Thanks.

    Anish Kumar writes:
    August 29th, 2009 at 12:30 am

    Possible causes would be you might not have the correct device token sending to your PHP code. Make sure you have stripped off the angle brackets and space in your device token that your receive from the APNS. Also check what is the return value of fwrite(). Hope this might help you. May be you can paste your code here.
    -Anish

ciri writes:
August 29th, 2009 at 7:32 pm

Now it don’t works:

Warning: stream_socket_client() [function.stream-socket-client]: SSL operation failed with code 1. OpenSSL Error messages: error:14094414:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate revoked

Warning: stream_socket_client() [function.stream-socket-client]: Failed to enable crypto

Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error)
Failed to connect 0

Yesterday it worked fine. I don’t have changed anything.

Adeem Basraa writes:
September 18th, 2009 at 11:04 pm

ok i have one question for you, i m testing application from my mac and it works fine but when i put this php code on server it gives me an error of
“Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection refused) in /home/content/14/4875914/html/code/push/apns.php on line 15
Failed to connect 111 Connection refused ”

any idea?

    Anish Kumar writes:
    September 18th, 2009 at 11:44 pm

    its most likely that you dont have the APNS SSL certificate setup properly and hence APNS is refusing connection from your server.
    -Anish

Mark writes:
September 20th, 2009 at 3:16 am

I desperately need your help.

I followed the instructions and everything works on my local machine which is great and thanks a lot for that! However, when I put the certificate.pem file and the php file from my local machine through FTP on my hosting it suddenly returns the following time-out:

Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out) in provider.php on line 23
Failed to connect 110 Connection timed out

I know there shouldn’t be anything wrong with the php nor the certificate due the fact it all works on my local machine with PHP and SSL installed, but as soon as I move it to my hosting company that time-out occures. So I am wondering, does the certificate only allows you to run the ’script’ on the computer you generated the certificate? If so, I am kinda screwed because I can only access the server of my hosting through FTP so there is no way for me to create a certificate there.

Could you give me some insides about this?

    Anish Kumar writes:
    September 25th, 2009 at 3:32 pm

    Sorry for the late reply. You have to create a new certificate for the new machine in which you are deploying. You might need SSH access to your hosting server to create those certificates. I have successfully deployed APNS on Amazon EC2. I created all the required certificates by accessing Amazon EC2 via SSH.

    All the best,
    -Anish

Youssef Henry writes:
September 26th, 2009 at 4:29 pm

my push notification provider server is linux any one could help me creating the ssl certificates from command line.

    Youssef Henry writes:
    September 26th, 2009 at 6:01 pm

    i fixed it but the alert and the sound work and the badge doesn’t work. any one can help.
    the fix is to easy i just copy the private key and the certificate to the server and convert them to pem on the server not on my machine.

      Kamal Challa writes:
      September 30th, 2009 at 4:30 pm

      Hi Youssef Henry,

      i tried the following code

      <?php
      $apnsHost = ‘gateway.sandbox.push.apple.com’;
      $apnsPort = 2195;
      $apnsCert = ‘apple_push_notification_production.pem’;

      $streamContext = stream_context_create();
      stream_context_set_option($streamContext, ’ssl’, ‘local_cert’, $apnsCert);

      $apns = stream_socket_client(’ssl://’ . $apnsHost . ‘:’ . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
      if($apns)
      {
      echo “Connection Established”;
      $deviceToken = ‘**********’;//masked

      $body = array();
      $body['aps'] = array(’alert’ => “test message”);
      //$body['aps']['badge'] = 1;

      $payload = json_encode($body);

      $apnsMessage = chr(0) . pack(”n”,32) . pack(’H*’, str_replace(’ ‘, ”, $deviceToken)) . pack(”n”,strlen($payload)) . $payload;
      print “sending message :” . $apnsMessage . “”;
      print “sending payload :” . $payload . “”;
      //fwrite($apns, $apnsMessage);

      }
      else
      {
      echo “Connection Failed”;

      echo $errorString;
      echo $error;
      }
      socket_close($apns);
      fclose($apns);
      ?>

      reply is Connection Established
      sending message :�� d^÷Îå0ZCd%1ÄuwOOYš’ÊÈ}ârðm¾Í�,{”aps”:{”\u2019alert\u2019″:”test message”}}
      sending payload :{”aps”:{”\u2019alert\u2019″:”test message”}}

      But am not able to get the notification

      any help?

Kamal Challa writes:
September 29th, 2009 at 4:30 pm

Hi

I tried sending the test message

$apnsHost = ‘gateway.sandbox.push.apple.com’;

************

$apnsMessage = chr(0).chr(0).chr(32).pack(’H*’, str_replace(’ ‘, ”, $deviceToken)).chr(0).chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);

*******

I got the message
Connection Establishedsending message :�� d^÷Îå0ZCd%1ÄuwOOYš’ÊÈ}ârðm¾Í�6{”aps”:{”\u2019alert\u2019″:”test message”,”badge”:1}}

but no luck from device side(no notification) any idea?

Mode writes:
October 3rd, 2009 at 1:10 am

Hi everybody, my code is
….
$msg=’1000 pdf files added, 2009-02-02′;
$payload=’{”aps”:{”alert”: $msg, “badge”:1,”sound”:”default”}}’;
$apnsMessage = chr(0) . chr(0) . chr(32) . pack(’H*’, str_replace(’ ‘, ”, $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
…..
A socket,devicetoken is valid, message is sent without error, But the message does not appear to my iphone.

bhoomesh writes:
October 21st, 2009 at 1:07 pm

Hi Anish,

iam kept apns.php code on windows machine. iam trying to access it from web browser, it is giving error as

“Unable to set local cert chain file `ck.pem’; Check that your cafile/capath settings include details of your certificate”

i kept both apns.php and ck.pem files in same folder inside server. how to resolve above error.

thanks in advance

    Anish Kumar writes:
    October 23rd, 2009 at 12:05 pm

    Hi Bhoomesh,
    You need to make sure that the certificate is generated from your windows machine. Most users create the certificate from their mac and then try to use them on their Windows Or Linux machines and end up facing this issue. You need to use openSSL tool to create the required certificate on your Windows or Linux machine.

    -Anish

david writes:
December 1st, 2009 at 12:45 pm

any comments for this post ?

Prasanna Gopinath writes:
November 4th, 2009 at 5:11 am

Hi Anish,

We have an app in AppStore with a APPID with a wild character ‘*’. Now we are doing Push Notification that cant take this wild character and we also want to upgrade the old app the new one.

What is your recommendation? We cant get a new APPID in which case we cant upgrade the old app to new app and we want to support push notification as well in the new app.

Thanks
–Prasanna

sathish writes:
December 2nd, 2009 at 5:19 pm

Hi Anish,

Can u please tell me how to get device token???

Thanks,
Sathish.

sathish writes:
December 2nd, 2009 at 7:05 pm

HI Anish,

one more question..

i am getting this error….
Error launching remote program: failed to get the task for process 1781.

can u please help in rectifying i..!!

Thanks,
-Sathish

    Anish Kumar writes:
    December 2nd, 2009 at 7:20 pm

    Hi Sathish,
    I had the same issue sometime back and I created a new development provisioning profile, deleted the old one. This fixed the problem. Give a try.
    Regards,
    -Anish

      sathish writes:
      December 2nd, 2009 at 8:46 pm

      HI Anish,

      I too tried it for more than 3 times creating new provisioning profile, but its showing “Error launching remote program”,

      Is there any other ways to get device token ??

      Thanks,
      -Sathish.

sathish writes:
December 3rd, 2009 at 11:46 am

Hi Anish,

I am not getting device token, can u please help me ??

Thanks,
-Sathish

    srinivasan writes:
    February 1st, 2010 at 11:20 am

    Hi Anish,

    The code was very use full to me

    Thanks,

david writes:
December 3rd, 2009 at 4:35 pm

http://www.iphonedevsdk.com/forum/iphone-sdk-development/34652-change-bundleidentifier-next-version.html

so for version update, don’t change Bundle Identifier but new profile is not an issue..

think so :)

mrmidi writes:
January 1st, 2010 at 10:25 am

There is an open source PHP/MySQL back-end for APNS. So if you want your own integration of push notifications on your own server, here you go :)

Main Link: http://www.easyapns.com
Google Code: http://code.google.com/p/easyapns/
Google Group: http://groups.google.com/group/easyapns

Jesse writes:
January 12th, 2010 at 9:26 pm

In case you appreciate constructive criticism, the font you use on this website is awful. The character width is too small to begin with, plus the kerning is too tight. I could use the info in this article, but in stead of straining my eyes to discover what I’m looking for, I’ll leave my opinion and move on.

Firat writes:
March 3rd, 2010 at 7:26 pm

Also there is an integration server tool for APNS called NS4app. You should check http://www.ns4app.com
Fastest messaging engine is the major feature of NS4app .

taraktas writes:
March 15th, 2010 at 7:43 pm

For professional support about server side, just visit http://www.ns4app.com

Kevin writes:
June 3rd, 2010 at 6:42 pm

Hi, I try the above code.

But get the below error:
Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out) in /home/kcs33109/public_html/testAPNS.php on line 21
Failed to connect 110

We are located in Australia. Any idea for how to solve this problem!

Thanks!

Kevin

    Anish Kumar writes:
    June 3rd, 2010 at 6:50 pm

    Hey Kevin,

    The error mostly occurs when the APNS certificate is not proper. Do make sure the path to the “ck.pem” file is correct(You need to give your full system path to the file: /Library/WebServer/Documents/apns/ck.pem)

    Hope it helps..!
    All the best,
    -Anish

      Kevin writes:
      June 5th, 2010 at 6:46 am

      Hi Anish,

      Thanks for your reply!
      My ck.pem file is in the same folder of testAPNS.php

      I tried
      stream_context_set_option($ctx, ’ssl’, ‘local_cert’, ‘ck.pem’);
      and
      stream_context_set_option($ctx, ’ssl’, ‘local_cert’, ‘/public_html/ck.pem’);

      but the same result:
      Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out) in /home/kcs33109/public_html/testAPNS.php on line 21
      Failed to connect 110

      I really don’t know how to solve it!

      Please help!

      Regards
      Kevin

        Anish Kumar writes:
        June 5th, 2010 at 10:51 am

        Hi Kevin,
        If your path to ck.pem file is correct, then for sure the ck.pem file was not created properly(probably was created using an invalid apns provision profile). Here is the possible things that you might have done wrong:
        1. Make sure you have created the certificate sigining request file(CertificateSigningRequest.certSigningRequest) from your SERVER from where you are invoking the PHP script. Most users usually create this file from their local development machine and then upload to iphone developer portal to create the aps_developer_identity.cer. (I strongly believe this is the case with you as I can see you are using a Linux server. Let me know if you need steps to create CertificateSigningRequest.certSigningRequest on a linux machine. )
        2. You might have missed any one of the step mentioned above in the tutorial.

        Hope this helps..!
        -Anish

          Kevin writes:
          June 5th, 2010 at 1:24 pm

          Hi Anish,

          Yes, I did create the certificate sigining request file from my computer and then upload to our host server (a linux machine).
          Please give me the steps to create CertificateSigningRequest.certSigningRequest on a linux machine.

          Thank you very much for all your help!

          Regards
          Kevin

          Kevin writes:
          June 6th, 2010 at 4:12 pm

          Hi Anish,

          Yes, I did create the certificate sigining request file from my computer and then upload to our host server (a linux machine).
          Please give me the steps to create CertificateSigningRequest.certSigningRequest on a linux machine.

          Thank you very much for all your help!

          Regards
          Kevin

            Anish Kumar writes:
            June 7th, 2010 at 4:28 pm

            For generating the APNS SSL certificate, we need to upload a certificate signing request (CSR) file to the iPhone developer portal. On Linux a CSR file can be generated by running the following commands on the SSH terminal you have logged in as described in section 5.5. Executing the command will prompt you to enter a pass phrase password as shown in the figure below.

            openssl genrsa -des3 -out server.key 2048

            Next use the server.key file and run the below command to create the .csr file that is uploaded to the iPhone developer portal.

            openssl req -new -key server.key -out server.csr

            Running these command prompts to enter various details like country, state city etc. Provide appropriate values to each of the options to create the CSR file. Upload the CSR file to the iPhone developer portal to create the APNS SSL certificate – aps_developer_identity.cer

            Hope this helps..!
            -Anish

              Kevin writes:
              June 8th, 2010 at 9:34 am

              Dear Anish,

              I can create the server.key file but can’t create the server.csr

              When I try this command to create the .csr file
              openssl req -new -key server.key -out server.csr
              it shows:
              Unable to load config info from /etc/pki/tls/openssl.cnf

              Anyway, our server is hosted in other company and they provide cPanel X to set up our server. I find that there is a SSL/TLS Manager. And I use this manager to create the Private Key. When I want to create the private key, I typed our website into the host field and use key size:2048. After that I use this key from SSL/TLS Manager to generate a server.csr file and I need to type in the country, state…. etc….

              Are these steps correct?

              I upload this server.csr file to iPhone developer portal to create the APNS SSL certificate- aps_developer_identity.cer
              and then double click this aps_developer_identity.cer to install into my local iMac. I open the keychain access and find that this certificate without any private key.

              What should I do next?

              Please help! Many thanks!

              Kevin

                Anish Kumar writes:
                June 14th, 2010 at 6:48 pm

                HI Kevin,

                Sorry for the late reply I was held up with loads of work. You should remember, all the keys and certificates are for the machine where you are finally deploying your code(where you want to run those php scripts).

                I used Amazon EC2 servers which gave me terminal access and i was able to deploy the APNS services without any hassles. Once you get the aps_developer_identity.cer, execute the following commands on your server.
                Generating .PEM file
                To create the file ck.pem file required to access the APNS service, we need to generate the ck.pem file by running the following command on the SSH terminal:
                openssl x509 -inform der -in aps_production_identity.cer -out ck.pem
                Once the ck.pem file is generated, PHP is ready to use that certificate to talk to push notification over the secure SSL channel.

                Hope this helps..!
                -Anish

Kevin writes:
June 16th, 2010 at 7:49 am

Hi Anish,

Thank you for your reply!

My hosting company block all my connection to Apple.
So I am building my linux server, I use ubuntu.

Thanks again!

Kevin

Kevin writes:
June 17th, 2010 at 1:15 pm

Hi Anish,

I have some questions about iLime, but can’t find any support email from your website.
Can you please give me an email address that I can contact iLime?

Thanks!

Kevin

Mahendera writes:
July 16th, 2010 at 4:36 pm

Hi

I have some issues about Apple Push Notification :

1. if I am using sandbox environment to push notification on iphone then how can I push messages to my multiple iphone devices for testing purpose.

2. I can make a build with ad-hoc provisioning profile to test application.

3. How can I send user preferred messages to specific user.

4. How can I send geo-based push notification to user.

Please reply if you have any idea about above issues.

Thanks in advance

    Fatih YASAR writes:
    July 30th, 2010 at 1:00 am

    @Mahendera,
    Check out to MonoPush project that accessible from http://monopush.com it seems they will provide what you requested.

    Regards

Speed_Code writes:
August 12th, 2010 at 1:01 pm

Hi,
i am working for the push requirement for the production server, have worked out with the development and it was working fine. In the Push i am done with all the certificates generation and all now for the push to the production server. I am getting the following error in my Mac Terminal Can anyone Guide me same ?

Warning: stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195 (php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known) in /Users/sapanvasanawala/Desktop/GlobaliSolution-Certifcates/apns.php on line 31
Failed to connect 0 php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known
Warning: stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195 (php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known) in /Users/mymachine/Desktop/Solution-Certifcates/apns.php on line 31…….

please let me know what should i do for getting out of it ……

Thanks

    Anish Kumar writes:
    August 12th, 2010 at 1:18 pm

    The SSl server address is correct, so the problem lies with your certificates. So here is the check list you need to see for your problem:

    1. Make sure you have created the certificate sigining request file(CertificateSigningRequest.certSigningRequest) from your SERVER from where you are invoking the PHP script. Most users usually create this file from their local development machine and then upload to iphone developer portal to create the aps_developer_identity.cer. (I strongly believe this is the case with you as I can see you are using a Linux server. Let me know if you need steps to create CertificateSigningRequest.certSigningRequest on a linux machine. )
    2. You might have missed any one of the step mentioned above in the tutorial.

    -Anish

Speed_Code writes:
August 12th, 2010 at 1:02 pm

Hi,
i am working for the push requirement for the production server, have worked out with the development and it was working fine. In the Push i am done with all the certificates generation and all now for the push to the production server. I am getting the following error in my Mac Terminal Can anyone Guide me same ?

Warning: stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195 (php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known) in /Users/-Certifcates/apns.php on line 31
Failed to connect 0 php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known
Warning: stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195 (php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known) in /Users/mymachine/Desktop/Solution-Certifcates/apns.php on line 31…….

please let me know what should i do for getting out of it ……

Thanks

Leave a Reply

Spam protection by WP Captcha-Free