IOS remote message push

Source: Internet
Author: User

IOS Push Basics

Apple uses a public key digital certificate to authenticate push requests from IOS applications, so you first need to create an authentication key and register them with Apple. I'll spend quite a bit of time in the next section to introduce this directly.

Next, you need to identify each device that installs the application and chooses to receive push notifications for that application. The sequence of work is as follows:

    1. A warning dialog box in the IOS app asks the user for permission to receive push notifications.
    2. If the user grants permission, the IOS app contacts the Apple Push Notification Service (APNs) to obtain an ID string that uniquely identifies the application installed on this device. (You can treat an ID like a recipient phone number in a traditional messaging scenario).
    3. The IOS app uploads the ID to your server application.
    4. When a server application needs to send a push message, it authenticates the Apple push server and then uses the ID obtained from Steps 2 and 3 to specify the recipient of the message.
    5. If the recipient device is online, it receives and processes the message. If the device is offline, the message is queued and then delivered the next time the device is online.

      APNs also enables your server application to periodically verify the list of application IDs that you have saved. This gives you the opportunity to remove users and IDs that later delete the application or modify its push selection status.

      This sounds like a lot of work, and it does. This is why there are services like Urban Airship, charge agent messages (see sidebar).

      After explaining how to register the application, I'll go into the details of developing an IOS push notification application and take advantage of the open source Java library and its server components.

An alternative to your own server: Urban Airship

Urban Airship is a service that lets you push messages without having to run your own server (see Resources). Upload the private key to Urban Airship and use its Web-based messaging console to push messages to the user. Urban Airship provides an IOS SDK that makes it easy for your application to register each installed device with its server, and these devices will appear in the message console. While Urban Airship can simplify your work, it is expensive, and you need to understand the basic push notification concepts.

APNs also enables your server application to periodically verify the list of application IDs that you have saved. This gives you the opportunity to remove users and IDs that later delete the application or modify its push selection status.

This sounds like a lot of work, and it does. This is why there are services like Urban Airship, charge agent messages (see sidebar).

After explaining how to register the application, I'll go into the details of developing an IOS push notification application and take advantage of the open source Java library and its server components.

Registering the Application

To register your application using push notifications, you first need to create a pair of private/public keys to authenticate the API calls to the APNs server. On a Mac, you can do this by using the KeyChain Access application. Select KeyChain Access > Certificate Assistant > Request a Certificate from a Certificate authorit Yto create a certificate signing request file. The request file contains the generated public key pair, and the corresponding private key is saved in KeyChain Access. Be sure to select the Saved to disk option in the dialog box, as shown in 1:

Figure 1. Generate a key pair and signature request from the KeyChain Access program on your MAC

Next, sign in to Apple's application configuration portal (see Resources) and upload your signature request file, which will be associated to the appropriate configuration profile. Most applications have a development configuration profile for testers and a production profile for the App Store, so you'll most likely generate and upload two signature requests. After you upload the signature request, the portal generates a digital certificate for you to download. The certificate contains the public key, and now APNs is recognized as being associated with your application. Figure 2 shows an example:

Figure 2. Digital certificates from Apple

Download the digital certificate, and double-click the file you want to download. KeyChain Access now automatically imports the digital certificate and associates it with the private key that you generated when you created the signing request. Figure 3 shows the public and private key pairs in KeyChain Access:

Figure 3. Public and private key pairs in KeyChain Access

Now, export the key pair as a file, using a format called Personal information Exchange (P12). When you create a p12 file, KeyChain Access requires you to specify a password to protect the private key. If you want to use a blank password, there is no problem.

From this point on, all API requests to the APNs push server must be in the P12 file?? The private key is encrypted and then digitally signed by the public key in the P12 file to verify that the API call is really generated by you. I'll show you how to use the keys later in this article to describe how to interact with the APNs server. (If you use Urban Airship, it will ask you to upload the P12 file and any password to its server so that it can send push messages on your behalf.) )

Now that you have a push certificate, you must re-download and reinstall your application configuration profile because the profile is now updated to support push notifications for your application.

Request and save a device token

Your IOS app needs to request user permission to receive push notifications on the devices it installs. Typically, you can do this in an application proxy through a simple API call, as shown in Listing 1:

Listing 1. Requesting a user License
[[UIApplication sharedapplication]    registerforremotenotificationtypes:        (Uiremotenotificationtypebadge |         Uiremotenotificationtypesound |          Uiremotenotificationtypealert)];

If the user grants a license, the application automatically contacts the APNs server for the device token. The token enables APNs to identify the specific application installed on that particular device as a message destination. This process is automatic and executes in the background. You don't need to write any code for it.

After the APNs server responds, the methods in the application proxy didRegisterForRemoteNotificationsWithDeviceToken are called, and the device token is passed in as a calling parameter. You must save the device token and upload it to your own push notification server, as shown in Listing 2:

Listing 2. Receive an ID and upload it to the server
-(void) application: (uiapplication*) Application Didregisterforremotenotificationswithdevicetoken: (NSData*)    Devicetoken {NSString *tokenstr = [Devicetoken description]; NSString *pushtoken = [[[[Tokenstr stringbyreplacingoccurrencesofstring:@ ' < ' withstring:@ '] StringByReplac   ingoccurrencesofstring:@ ">" withstring:@ ""] stringbyreplacingoccurrencesofstring:@ "" withstring:@ ""] retain];    Save the token to server nsstring *urlstr = [NSString stringwithformat:@ "Https://%@/push_token", Ringfuldomain];    Nsurl *url = [Nsurl urlwithstring:urlstr];           Nsmutableurlrequest *req = [Nsmutableurlrequest Requestwithurl:url];   [Req sethttpmethod:@ "POST"];   [Req setvalue:@ "application/x-www-form-urlencoded" forhttpheaderfield:@ "Content-type"];   Nsmutabledata *postbody = [Nsmutabledata data]; [Postbody appenddata:[[nsstring stringwithformat:@ "username=%@", username] datausingencoding:nsutf8stringencoding]    ]; [Postbody appenddata:[[nsstring stringwithformat:@ "&token=%@", Pushtoken] datausingencoding:nsutf8stringencoding];   [Req Sethttpbody:postbody]; [[Nsurlconnection alloc] initwithrequest:req delegate:nil];}

Ideally, you associate a token with some information that marks a user, such as a personal user name on your system, so that your server knows who to send the message to later. (You can think of it like associating a phone number with a personal name.) If you do not have a token associated with your own user identification information, you can still send messages to these devices, but you cannot customize the message for each user because you have a letter token string for the target device.

The server should keep the token and its associated identity information in the database. In most applications, it is saved in the user profile database.

Send a push message

To send a push message to your server:

    1. Find a list of target application IDs for outgoing messages
    2. Personalize messages for each recipient based on the recipient's user profile
    3. Contact APNs Messaging Server

The Web service API for the APNs server is complex. Fortunately for Java developers, the open source Javapns library makes it easier to use. See Resources for Javapns and download and documentation links.

The code in Listing 3 shows how to send a text-like message to the device using the Javapns library:

Listing 3. Send a push message
String[] devices = {"token1", "token2}"; list<pushednotification> notifications = Push.alert ("Hello world!", "keypair.p12", "password ", false, devices);

The main interface method of the Javapns library is a Push static method in the class. APNs allows you to embed a variety of content in your messages. Refer to the IOS Push message guide for a complete list of supported payload types (see Resources). The Push APNs class provides a convenient method for each type of message, and it translates the message into the JavaScript Object Notation (JSON) format that is accepted by the server. In Listing 3, the keypair.p12 P12 file that is exported from KeyChain Access is the password for the password p12 file. devicesAn array is a list of device tokens that are received from an IOS application. All of these devices will receive this push message. The value in the parameter false specifies that the message should be sent to the APNs Development server ( sandbox ) instead of its production server. (Recall that you typically create a P12 key pair for the sandbox, creating a different key pair for the production server.) )

The value returned by the method call is a PushedNotification list of objects that you can use to determine the status of the push delivery, as shown in Listing 4:

Listing 4. Check the status of the push delivery
for (Pushednotification notification:notifications) {    if (notification.issuccessful ()) {/        * Apple accepted the Notification and should deliver it */    } else {        String Invalidtoken = Notification.getdevice (). GetToken ();        /* ADD code here to remove Invalidtoken from your database */    }}

If the notification object tells you that a device token is no longer active, for example, if the user removes the application from the device, or if notification is disabled in the application settings, you should remove the token from the database so that you no longer send a message to it.

Another way to keep the latest active device Token list is to have your server application periodically check the APNs server. Listing 5 shows how to query the APNs feedback service and use Javapns to receive a list of invalid device tokens from the APNs sandbox:

Listing 5. Check to update the active device token
list<device> inactivedevices = Push.feedback ("Keypair.p12", "password", false);/* Remove inactive Devices from your own list of devices */

It is important not to waste resources in sending messages to devices that have deleted your application, or to choose devices that do not receive notifications.

Other considerations

Push notifications cannot be tested on the IOS emulator; You must deploy the application to the actual device to test it. Because the digital certificate that is used to authenticate the message is bundled into the application's configuration profile, you need to test it with a development certificate in the development or temporary distribution application. After the application is approved and available in the app Store, you must switch to the production certificate.

Furthermore, it is important to understand that customizing and sending push messages for users in large databases is a resource-intensive effort. For example, a million-user-level database is traversed every 5 seconds to identify 10 users who need to receive messages at that time, which is very expensive. The server-side infrastructure requires careful design and planning to support frequent push notifications to a large number of users. Conversely, sending a push message to 1 million users at a time can generate a lot of traffic, so it's better to handle this scenario by using a thread pool instead of blocking a separate thread. The Javapns Library provides a simple API that uses the thread pool to push messages to a large number of devices at the same time.

Conclusion

Push technology lets your server application bypass the telco carrier and send messages directly to the IOS device's application over the Internet. While it is not trivial to implement push notifications (client SSL certificates have complex authentication requirements for Apple servers), help from third parties, such as Urban Airship and Javapns, can make it easier to send notifications. SMS and MMS have their own location and are still more reliable than push technology, but you can make your IOS app richer and more functional by implementing push messages.

IOS remote message push

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.