iOS Push Notification with Pictures

Generate the Certificate Signing Request file

First you must generate the Certificate Signing Request (CSR) file, which is used by Apple to generate a signed certificate.

From the Utilities folder, run the Keychain Access tool.
Click Keychain Access, expand Certificate Assistant, then click Request a Certificate from a Certificate Authority….

f11labz ios1

3. Select your User Email Address and Common Name , make sure that Saved to disk is selected, and then click Continue. Leave the CA Email Address field blank as it is not required.

Xcode

f11labz ios2

4. Select your User Email Address and Common Name , make sure that Saved to disk is selected, and then click Continue. Leave the CA Email Address field blank as it is not required.

Xcode

f11labz ios3

This saves the CSR file in the selected location; the default location is in the Desktop. Remember the location chosen for this file.

Next, you will register your app with Apple, enable push notifications, and upload this exported CSR to create a push certificate.

Register your app for push notifications

To be able to send push notifications to an iOS app from mobile services, you must register your application with Apple and also register for push notifications.

1. If you have not already registered your app, navigate to the iOs provisioning profile at the Apple Developer Center, log on with your Apple ID, click Identifiers, then click App IDs, and finally click on the + sign to register a new app.

ios4 f11labz

2.Type a name for your app in Description, enter the value MobileServices.Quickstart in Bundle Identifier, check the “Push Notifications” option in the “App Services” section, and then click Continue. This example uses the ID MobileServices.Quickstart but you may not reuse this same ID, as app IDs must be unique across all users. As such, it is recommended that you append your full name or initials after the app name.

ios5 f11labz

This generates your app ID and requests you to Submit the information. Click Submit

ios6 f11labz

Once you click Submit, you will see the Registration complete screen, as shown below. Click Done.

f11labz ios7

NOTE:

If you choose to supply a Bundle Identifier value other than MobileServices.Quickstart, you must also update the bundle identifier value in your Xcode project.

3.Locate the app ID that you just created, and click on its row.

ios8 f11labz

Clicking on the app ID will display details on the app and app ID. Click the Settings button.

ios9 f11labz

4.Scroll to the bottom of the screen, and click the Create Certificate… button under the section Development Push SSL Certificate.

ios10 f11labz[/ca[tion]

This displays the “Add iOS Certificate” assistant.

NOTE:

This tutorial uses a development certificate. The same process is used when registering a production certificate. Just make sure that you set the same certificate type when you upload the certificate to Mobile Services.

5.Click Choose File, browse to the location where you saved the CSR file that you created in the first task, then click Generate.

[caption id="" align="alignnone" width="600"] ios 11 f11labz

6.After the certificate is created by the portal, click the Download button, and click Done.

ios 12 f11labz

This downloads the signing certificate and saves it to your computer in your Downloads folder.

ios13 f11labz

By default, the downloaded file a development certificate is named aps_development.cer

7. Double-click the downloaded push certificate aps_development.cer.

This installs the new certificate in the Keychain, as shown below:

ios 14 f11labz

This installs the new certificate in the Keychain, as shown below:

ios15 f11labz

NOTE:

The name in your certificate might be different, but it will be prefixed with Apple Development iOS Push Notification Services:

Later, you will use this certificate to generate a .p12 file and upload it to Mobile Services to enable authentication with APNS.

Create a provisioning profile for the app

  1. Select Provisioning Profiles, select All, and then click the + button to create a new profile. This launches the Add iOS Provisiong Profile Wizard

ios16 f11labz

2. Select iOS App Development under Development as the provisioning profile type, and click Continue

ios17 f11labz

3. Next, select the app ID for the Mobile Services Quickstart app from the App ID drop-down list, and click Continue

ios18 f11labz

4. In the Select certificates screen, select the certificate created earlier, and click Continue.

ios19 f11labz

5. Next, select the Devices to use for testing, and click Continue

ios20 f11labz

6.Finally, pick a name for the profile in Profile Name, click Generate, and click Done

ios21 f11labz

This creates a new provisioning profile.

7. In Xcode, open the Organizer select the Devices view, select Provisioning Profiles in the Library section in the left pane, and then click the Refresh button at the bottom of the middle pane.

ios22 f11labz

8. Under Targets, click Quickstart, expand Code Signing Identity, then under Debug select the new profile.

ios23 f11labz

This ensures that the Xcode project uses the new profile for code signing. Next, you must upload the certificate to Azure.

Configure Mobile Services to send push requests

After you have registered your app with APNS and configured your project, you must next configure your mobile service to integrate with APNS.

  1. In Keychain Access, right-click the new certificate, click Export, name your file QuickstartPusher, select the .p12 format, then click Save.

Make a note of the file name and location of the exported certificate.

Making a PEM File

So now you have three files:

  • The CSR
  • The private key as a p12 file (PushChatKey.p12)
  • The SSL certificate, aps_development.cer

Store these three files in a safe place. You could throw away the CSR but in my opinion it is easier to keep it. When your certificate expires, you can use the same CSR to generate a new one. If you were to generate a new CSR, you would also get a new private key. By re-using the CSR you can keep using your existing private key and only the .cer file will change.

You have to convert the certificate and private key into a format that is more usable. Because the push part of our server will be written in PHP, you will combine the certificate and the private key into a single file that uses the PEM format.

The specifics of what PEM is doesn’t really matter (in fact, I have no idea) but it makes it easier for PHP to use the certificate. If you write your push server in another language, these following steps may not apply to you.

You’re going to use the command-line OpenSSL tools for this. Open a Terminal and execute the following steps.

Go to the folder where you downloaded the files, in my case the Desktop:


$ cd ~/Desktop/

Convert the .cer file into a .pem file:


$ openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem

Convert the private key’s .p12 file into a .pem file:


$ openssl pkcs12 -nocerts -out PushChatKey.pem -in PushChatKey.p12



Enter Import Password: 

<strong>MAC verified OK</strong>

Enter PEM pass phrase:

Verifying - Enter PEM pass phrase: 

You first need to enter the passphrase for the .p12 file so that openssl can read it. Then you need to enter a new passphrase that will be used to encrypt the PEM file. Again for this tutorial I used “pushchat” as the PEM passphrase. You should choose something more secure.

Note: if you don’t enter a PEM passphrase, openssl will not give an error message but the generated .pem file will not have the private key in it.

Finally, combine the certificate and key into a single .pem file:


$ cat PushChatCert.pem PushChatKey.pem > ck.pem

At this point it’s a good idea to test whether the certificate works. Execute the following command:


$ telnet gateway.sandbox.push.apple.com 2195</strong>

Trying 17.172.232.226...

Connected to gateway.sandbox.push-apple.com.akadns.net.
Escape character is '^]'.



This tries to make a regular, unencrypted, connection to the APNS server. If you see the above response, then your Mac can reach APNS. Press Ctrl+C to close the connection. If you get an error message, then make sure your firewall allows outgoing connections on port 2195.

Let’s try connecting again, this time using our SSL certificate and private key to set up a secure connection:


$ openssl s_client -connect gateway.sandbox.push.apple.com:2195 

-cert PushChatCert.pem -key PushChatKey.pem

Enter pass phrase for PushChatKey.pem:

You should see a whole bunch of output, which is openssl letting you know what is going on under the hood.

If the connection is successful, you should be able to type a few characters. When you press enter, the server should disconnect. If there was a problem establishing the connection, openssl will give you an error message but you may have to scroll up through the output to find it.

Note: There are two different APNS servers: the “sandbox” server that you can use for testing, and the live server that you use in production mode.

Above, we used the sandbox server because our certificate is intended for development, not production use.

Xcode

A sample application is needed to receive push notification. One can do it with any application

designed by him in Xcode.

If you want to create everything yourself, here are the steps involved :

1) start up Xcode

2) Go to File\New\New Project.

3) Select iOS\Application\View-based Application, and click Next.

4) Enter product name and remember bundle identifier. ( A bundle identifier is needed to

generate certificate.

5) Select devices for which the code will run.

6) The following code segment will communicate with web service :


(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:

(NSDictionary *)launchOptions

{

// Override point for customization after application launch.

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:

(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |

UIRemoteNotificationTypeSound)];

return YES;

}

- (void)application:(UIApplication *)application

didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken

{

NSString *deviceTokenString = [NSString stringWithFormat:@"%@", deviceToken];

NSLog(deviceTokenString);

}

Local Server

Push notifications are always sent by a server. For development you can use your Mac as the

server but for production use, you need at least something like a VPS (Virtual Private Server).

Push notification is a short message that consists of the device token, a payload, and a few

other bits and bytes. The payload contains the actual data you will be sending around.

A device token is the unique device id of the device you are intending to send the notification.

A payload is the segment containing the data you will be throwing around. A sample payload

is as follows :

[Java]

{

“aps” :

{ “alert” : “‘.$message.'”,

“badge” : 1,

“sound” : “bingbong.aiff”

}

}

[/Java]

If you do not have a web server, you can enable it on your Mac using the following steps :

1) Go to finder.

2) Navigate to /etc/apache2.

3) Look for httpd.conf file.

4) Open and uncomment the following line :

#LoadModule php5_module libexec/apache2/libphp5.so

5) Start Web Sharing by opening System Preferences, clicking on “Sharing”, and

checking “Web Sharing”.

The above steps will enable your web server. Now drag the .pem file you generated (by

concatenating the certificate and key pair files ) into the same folder where you php file

Run the php file on your brwoser and notification will be sent to desired device.

I am sharing the php file which I have used in developing the APNs for further use.It will

provide help to users who are not an expert in php script.

if($_POST['message']){

$deviceToken = '5e26bbd4 62d89c5d 0a18a307 8440fe3f 538e9a79 5e5dd21a

57740795 66f21960';

$message = stripslashes($_POST['message']);

$payload = '{

"aps" :

{ "alert" : "'.$message.'",

"badge" : 1,

"sound" : "bingbong.aiff"

}

}';
$ctx = stream_context_create();

stream_context_set_option($ctx, 'ssl', 'local_cert',

'server_cerificates_bundle_sandbox.pem');

//stream_context_set_option($ctx, 'ssl', 'passphrase', 'gaurav');

$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 "Notifications sent!";

}

$devArray = array();

$devArray[] = $deviceToken;

foreach($devArray as $deviceToken){

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

}

?>

Hiccups :

One can face a lot of problems because of certificates and firewall. I have mentioned a few of

them here.

➢ Firewall Block → port 2195 not opening

Message Thrown : Warning: stream_socket_client() [function.stream-socket-client]:

unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Operation timed

out)

➢ Certificates not valid → port opening properly

Message Thrown : stream_socket_client() [function.stream-socket-client]: Failed to

enable crypto.

There can be lot of other error messgaes but these two are worth mentioning.

Aniruddha Mukherjee

Aniruddha Mukherjee

Android and iOs consultant.

More Posts

Follow Me:
TwitterFacebookLinkedInGoogle Plus

Add a Comment

HTML Snippets Powered By : XYZScripts.com