Push Notification

Push Notifications


In iOS, apps can’t do a lot in the background. Apps are only allowed to do limited set of activities so battery life is conserved.
But what if something interesting happens and you wish to let the user know about this, even if they’re not currently using your app?
For example, maybe the user received a new tweet, their favorite team won the game, or their dinner is ready. Since the app isn’t currently running, it cannot check for these events.
Luckily, Apple has provided a solution to this. Instead of your app continuously checking for events or doing work in the background, you can write a server-side component to do this instead.
And when an event of interest occurs, the server-side component can send the app a push notification! There are three things a push notification can do:
  • Display a short text message
  • Play a brief sound
  • Set a number in a badge on the app’s icon

Getting push to work for your app takes quite a bit of effort. This is a puzzle with many pieces. Here is an overview 


  1. An app enables push notifications. The user has to confirm that he wishes to receive these notifications.
  2. The app receives a “device token”. You can think of the device token as the address that push notifications will be sent to.
  3. The app sends the device token to your server.
  4. When something of interest to your app happens, the server sends a push notification to the Apple Push Notification Service, or APNS for short.
  5. APNS sends the push notification to the user’s device.

When the user’s device receives the push notification, it shows an alert, plays a sound and/or updates the app’s icon. The user can launch the app from the alert. The app is given the contents of the push notification and can handle it as it sees fit.

Note ->
Local notifications are available in iOS only.
Push notifications are available in both iOS and, beginning with OS X v10.7 (Lion), OS X.


Anatomy of a Push Notification

Your server is responsible for creating the push notification messages, so it’s useful to know what they look like.
A push notification is a short message that consists of the device token, a payload, and a few other bits and bytes. The payload is what we are interested in, as that contains the actual data we will be sending around.
Your server should provide the payload as a JSON dictionary. The payload for a simple push message looks like this:
{"aps":{"alert":"Hello, world!","sound":"default"}}

Push notifications whose payload exceeds 256 bytes will not be accepted by APNS.


StepByStep

I advise you to follow them exactly. Most of the problems people have with getting push notifications to work are due to problems with the certificates.


1. Generate CSR Certificate Signing :-

Digital certificates are based on public-private key cryptography. You don’t need to know anything about cryptography to use certificates, but you do need to be aware that a certificate always works in combination with a private key.
The certificate is the public part of this key pair. It is safe to give it to others, which is exactly what happens when you communicate over SSL. The private key, however, should be kept… private. It’s a secret. Your private key is nobody’s business but your own. It’s important to know that you can’t use the certificate if you don’t have the private key.
Whenever you apply for a digital certificate, you need to provide a Certificate Signing Request, or CSR for short. When you create the CSR, a new private key is made that is put into your keychain. You then send the CSR to a certificate authority (in this case that is the iOS Developer Portal), which will generate the SSL certificate for you based on the information in the CSR.
Open Keychain Access on your Mac (it is in Applications/Utilities) and choose the menu option Request a Certificate from a Certificate Authority….


If you do not have this menu option or it says “Request a Certificate from a Certificate Authority with key”, then download and install the WWDR Intermediate Certificate first. Also make sure no private key is selected in the main Keychain Access window.

Then in next window fill detail and Check Saved to disk and click Continue. Save the file as “yourCSR.certSigningRequest”.

If you go to the Keys section of Keychain Access, you will see that a new private key has appeared in your keychain. Right click it and choose Export.



Save the private key as PushKey.p12 and enter a passphrase(password, you can enter pushchat).

2. Making AppID and SSL certificate

Log in to the iOS Dev Center and “Select the Certificates, Identifiers and Profiles” from the right panel.

Now, you are going to make a new App ID. Each push app needs its own unique ID because push notifications are sent to a specific application. (You cannot use a wildcard ID.)

Fill the following details:
  • App ID DescriptionpushNotify
  • App Services Check the Push Notifications Checkbox
  • Explicit App ID: com.yourCompany.push
After you’re done filling all the details press the Continue button. You will be asked to verify the details of the app id, if everything seems okay click Submit

In a few moments, you will generate the SSL certificate that your push server uses to make a secure connection to APNS. This certificate is linked with your App ID. Your server can only send push notifications to that particular app, not to any other apps.

After creating appId your select your AppId from the section this will look like


Notice in the “Push Notification” row, there are two gray lights that say “Configurable” in the Development and Distribution column. This means your App ID can be used with push, but you still need to set this up. Click on the Setting button to configure these settings.


Scroll down to the Push Notifications section  , click on check box and select the Create Certificate button in the Development SSL Certificate section.
IF you already created your CSR then click on continue otherwise follow step on the screen.
On next screen upload your CSR then click on Generate 


When you are ready to release your app, repeat this process for the production certificate. The steps are the same.

Note: The production certificate remains valid for a year, but you want to renew it before the year is over to ensure there is no downtime for your app.

double-clicking the downloaded development.cer file. If you do, you’ll see that it is now associated with the private key.Now export your certificate you will get development.p12, save this at the place where you saved your private key(PushKey.p12).

3. Making PEM

So now you have three files:
  • The CSR
  • The private key as a p12 file (PushKey.p12)
  • The SSL certificate, development.p12
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/

Then you use these commands to generate the cert and key in Mac’s Terminal for PEM format

openssl pkcs12 -clcerts -nokeys -out cert.pem -in development.p12
openssl pkcs12 -nocerts -out key.pem -in PushKey.p12

Then combine the certificate and key
cat cert.pem key.unencrypted.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
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.
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.

4. Making Provisioning Profile

You’re not yet done with the iOS Dev Center. Click the Provisioning Profiles button in the sidebar and click the + button.
This will open up the iOS provisioning profile wizard.

1.Select Type
Select the “iOS App development” option button in the first step of the wizard and press Continue.
2.Configure
Select the pushNotify id that you created in the previous section. This will ensure that this provisioning profile is explicitly tied to the pushNotify
3. Generate
4. Select Device
5.Name of Profile
6.Download

Add the provisioning profile to Xcode by double-clicking it or dragging it onto the Xcode icon.


Now register your application for pushnotification
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Let the device know we want to receive push notifications
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
        (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

    return YES;
}

Build & Run the app. You need to do this on your device because the simulator does not support push notifications. Xcode should automatically have selected the new provisioning profile. If you get a code sign error, then make sure the proper profile is selected in the Code Signing build settings.
When the app starts and registers for push notifications, it shows a message to inform the user that this app wishes to send push notifications.

There is one more thing you need to add in order to be able to receive push notifications.
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
 NSLog(@"My token is: %@", deviceToken);
}
 
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
 NSLog(@"Failed to get token, error: %@", error);
}

When your app registers for remote (push) notifications, it tries to obtain a “device token”. This is a 32-byte number that uniquely identifies your device. Think of the device token as the address that a push notification will be delivered to.
Run the app again and you should see something like this in Xcode’s console window:
My token is: 
<f4707740 cf74fbeb c25d49b7 85894e33 5f6aa01d a5ddb387 462c7eaf 61bb78ad>
The token is an opaque binary data structure, stuffed into an NSData object. Apple doesn’t want you to mess around with its internals. For our purposes it is enough to know that it is currently 32 bytes long. As you can see above, the token can be represented by 64 hexadecimal characters. You will be using it in that format, although you still strip off the brackets and leave out the spaces.
If you run the app in the simulator, the application:didFailToRegisterForRemoteNotificationsWithError: method will be called as push notifications are not supported in the simulator.
That’s it for the app. There is one more thing to do and then you can finally see some push notifications in action!

Sending Your First Push Notification

As I’ve mentioned a few times before, you need to set up a server that sends the push notifications to your app. For this first test, you’re not going to set up a server just yet. Instead, I’ll give you a very simple PHP script that sets up a connection to APNS and sends a push notification to a device token that you specify. You can run this straight from your Mac.
Download the SimplePush code and unzip it. You need to make some changes to simplepush.php.
// Put your device token here (without spaces):
$deviceToken = '0f744707bebcf74f9b7c25d48e3358945f6aa01da5ddb387462c7eaf61bbad78';
 
// Put your private key's passphrase here:
$passphrase = 'pushchat';
 
// Put your alert message here:
$message = 'My first push notification!';
You should copy the device token from the app into the $deviceToken variable. Be sure to leave out the spaces and brackets; it should just be 64 hexadecimal characters. Put your private key’s passphrase into $passphrase, and the text you wish to send in $message.
Copy your ck.pem file into the SimplePush folder. Remember, the ck.pem file contains both your certificate and the private key.
Then open a Terminal and type:
$ php simplepush.php
If all goes well, the script should say:
Connected to APNS
Message successfully delivered
And within a few seconds you should receive your first push notification:

Note that you won’t see anything when the app is open. The push message is delivered but you did not build anything in the app to handle it yet. Close the app and try again.
If the simplepush.php script exits with an error message, then check that you have made the PEM file correctly, and that you can connect to the sandbox server without problems (see above).



Here is the link i learn about push notification, my tutorial is combination of both site
and




Other link

Comments

Popular posts from this blog

Launch iPhone simulator without Xcode.

How to Make REST api call in Objective-C.

id vs NSObject