This is a tutorial written by MatthijsHollemans of the iOS tutorial team. MatthijsHollemans is an experienced iOS developer and designer. In iOS systems, operations that can be performed by programs running in the background are very limited. This restriction is used to save cell phone batteries. However, if you need to give
This is a tutorial written by Matthijs Hollemans of the iOS tutorial team. Matthijs Hollemans is an experienced iOS developer and designer. In iOS systems, operations that can be performed by programs running in the background are very limited. This restriction is used to save cell phone batteries. However, if you need to give
This is a tutorial written by Matthijs Hollemans of the iOS tutorial team. Matthijs Hollemans is an experienced iOS developer and designer.
In iOS systems, operations that can be performed by programs running in the background are very limited. This restriction is used to save cell phone batteries.
However, what if you want to push messages to users without using your program?
For example, the user received a message from Twitter that his favorite team won the game or that his dinner was ready. Because the user is not using our program, the program itself cannot listen to these events.
Fortunately, the Apple system has a solution to this problem. You do not need to keep the program listening to events or running operations in the background. You only need to write a server component to complete this task.
When a specific event occurs, the server component can send a push message to our program! Push information can do the following:
- Display a message
- Play a short piece of music prompt
- Place a number sign on the side of the small icon of the program
You can combine these options at will. For example, you can play a prompt and place a number sign without displaying any information.
In this two-part tutorial, you will use the apple push server (APNS) to complete a simple program with the message push function.
In the first part, you will learn how to receive pushed information.
This tutorial is intended for intermediate or advanced iOS developers. If you are still getting started with iOS, you should first take a look at some preliminary tutorials on this website. in addition, I suggest you take a look at the following two tutorials (or have similar experience ):
- How to Write simple PHP/MySQL network services for iOS programs
- How to Use Network Services in iOS programs
Let's get started!
Summary
It takes a lot of effort to add information push to your app. This task has many parts. The following is a summary:
- The program enables the message push function. The user must confirm that he wants to accept the push information.
- The program receives a "device tag code ". You can regard the device tag as the push information address.
- The program sends the device tag code to the server.
- When any event about your program occurs, the server sends the information to the push Information Service (APNS) of apple ).
- APNS pushes this information to the user's device.
When a user's device receives this message, a prompt window is displayed, indicating the number of playing prompts or updating apps. You can enable the app directly in the prompt window. Our app takes the content of the push information from here and can customize the logic for processing this information.
Someone may ask, if there is a local prompt and multiple task execution in iOS4, is the push information prompt still useful? Answer: "Of course "!
Local prompts can only be used for scheduled events. Unlimited background operations are only applicable to online calls, navigation, and background music apps. If you want to prompt the user information when the program is running in the background, you still need to use the push information prompt.
In this tutorial, I will explain in detail how push information prompts are implemented and how to use it in your app. There are many things to learn. Let's start now!
Push information Prompt preparation
Add the push information prompt to your app. You need:
An iPhone or iPad.You need a real device because the push information prompt cannot be used in the simulator.
You must be a registered iOS developer.Each app to add push information requires a new App ID, provisioning profile, and SSL certificate. You can perform these operations on the iOS Provisioning Portal.
If you want to follow the example in this tutorial, you need to create a new provisioning profile and SSL Certificate; you cannot use my. It is important to obtain the correct certificate. I will explain how to obtain the certificate step by step.
A server connected to the Internet.The push information is sent by this server. During development, you can use your Apple computer as the server (we will do this in this tutorial), but after the app goes online, you need at least one VPS (virtual private server ).
A simple Shared Server account is not enough. You need to be able to run backend threads on the server, install SSL certificates, and establish TLS connections on specific ports externally.
Most shared server providers won't let you do this. Therefore, I strongly recommend that you use a Linode server.
Parse message PUSH Service/h2>
Your server is responsible for creating pushed messages, so let's take a look at how this server works.
A push message contains the device tag Code, information load, and some other bytes. The information load is the PUSH message we want to send to the device.
The information load provided by your server should be in the JSON dictionary format. A simple push information load should be like this:
{"aps":{"alert": "Hello, world!","sound": "default"}}
If you do not understand JSON, you only need to know that a code block separated by the "{}" symbol represents a dictionary (similar to NSDictionary) corresponding to the key and value ).
Our information is such a dictionary. The dictionary must contain at least one object, "aps ". "Aps" is a dictionary. "Aps" contains two keys: "alert" and "sound. When the device receives this message, the program should display a pop-up message: "Hello, world !" And a standard tone is issued.
You can also add other objects to the "aps" dictionary to set the message. For example:
{"aps":{"alert":{"action-loc-key": "Open","body": "Hello, world!"},"badge": 2}}
Local and push information programming guide.
Push information should be concise; that information load should not exceed 256 bytes. In this way, there is usually enough space to send an SMS message or a twitter message. The correct server will not waste valuable load space for transmitting line breaks and spaces, so your service should send such information:
{"aps":{"alert":"Hello, world!","sound":"default"}}
This is difficult for people to understand, but it saves more space. Apple APNS does not accept push messages of over 256 bytes.
Error message push
The push message is not reliable!
Too unreliable!Even if the APNS server receives information, the push message may not be successfully transmitted to the user's device.
Your server cannot obtain the message status after pushing messages to APNS. The actual push time of a message is not necessarily the same. It may take several seconds or half an hour.
In addition, the user's iPhone does not receive push information at any time. They may be in a wireless network that cannot receive the PUSH Service from Apple, probably because the corresponding network port is closed or the user's mobile phone is shut down.
The push service of Apple will try to retry messages that are not delivered after the mobile phone is re-launched, but there is a time limit. When the time limit expires, we will never lose the prompt!
After you see the bill for Apple PUSH Service
Expensive!If many users or pushed information need to be retrieved from other places, the Service may be expensive.
For example, if you control the RSS source. Because you will know when New RSS will be available, you can easily push information to users at appropriate times.
However, what if your program allows users to enter custom RSS URLs? In this case, you need to have your own solution to detect the RSS information.
In fact, your server needs to constantly access these addresses to detect new RSS messages. If you have many users, You need to constantly add new servers to detect and send information. This will soon become very expensive.
After the theoretical questions are discussed, let's start to practice. But before doing something interesting-programming, we still need to complete some boring settings on the iOS developer portal.
Provisioning Profiles and various certificates
An apple PUSH Service requires a certificate!
In order for your program to use the PUSH Service, we need to establish a provisioning profile specifically used for this service. In addition, your server also needs to establish a connection with Apple's push server through the SSL certificate.
The provisioning profile corresponds to the SSL Certificate one by one, and can be used only when there is a valid App ID. This is to ensure that your server can only send push information to this specific program, but not to any other program.
It is worth noting that a program must use different provisioning profiles during development and release. There are also two types of server certificates:
- Development Time. If your program runs in Debug mode and uses the provisioning profile of the development phase (the value of the Code Signing Identity attribute is "iPhone Developer "), then, your server must use the development certificate.
- Production TimeIf the program has been published on the Apple Store (the value of the Code Signing Identity attribute is "iPhone Distribution"), the server must use the certificate in the production phase. If these two messages are mixed up, the push prompt cannot reach your program.
In this tutorial, we will only use the profile and certificate at the time of development.
Generate a Certificate Signing Request (Certificate Application)
Do you still remember how you registered the iOS development plan on the iOS developer website and obtained the development certificate? What we need to do below is similar to that. However, I suggest you follow me step by step to complete this operation. Because most problems occur with the certificate.
E-certificates are encrypted based on both public and private keys. You do not need to know the encryption process, but you need to know that the certificate must be used together with a private key to be valid.
That certificate is the public part of this set of keys. Therefore, it is okay to give this part to others. This is what you need to do when you use SSL for communication. However, the private key must be kept confidential. This secret cannot be known to anyone. If you do not have this key, the certificate becomes invalid.
When you apply for an e-Certificate, you need to submit a Certificate Signing Request (CSR. When you generate a CSR, a new private key is generated and put in the keychain of your computer. Then you send this CSR to a certificate certification website (in our case, this website is the developer portal of Apple ). This website uses CSR to generate an SSL certificate.
Open the Keychain Access program on your Mac (in the Applications/Utilities subdirectory), and selectRequest a Certificate from a Certificate Authority...It means to obtain the certificate from the certificate authority.
WWDR Intermediate Certificate. Note that do not select any private key in the main Keychain Access window.
Then you should see a window similar to the following:
Enter your email address. I once heard that you should use the same email address as when you applied for the iOS Developer Program, but it should be fine with any email address.
Enter "PushChat" in the Common Name column. You can enter any Name as the public Name, but it is best to select some representative names. In this way, we can quickly find this private key.
InSaved to disk(Save to hard disk. Save it as "PushChat. certSigningRequest ".
If you come to the Keychain Access's Keys section, you should see a new private key that you just generated. Right-click and export it.
Name the export file "PushChatKey. p12" and enter a password.
For convenience, my password is "pushchat ". But to better protect this p12 file, you should select a password that is harder to guess. Private keys must be private keys, right? But you must remember to add the password. Otherwise, the private key still cannot be used.
Create an App ID and obtain an SSL Certificate
Log on to the iOS backup portal.
First, we need to create a new App ID. Every app that uses push information service requires a unique ID, because only in this way can the pushed information prompt be sent to the correct program. (Here, you cannot use a wildcard ID .)
Select"App IDs"And then click"New App ID"Button.
The content is as follows:
- Description: PushChat
- Bundle Seed ID: Generate New
- Bundle Identifier: Com. hollance. PushChat
You 'd better choose your own Bundle Identifier instead of using my, for example, "com. Your Website. PushChat ". You will use this Bundle Identifier in Xcode later.
Soon, we will generate an SSL certificate. Your server uses this certificate to establish a secure connection with Apple's push server. This certificate is bound with your App ID so that your server can only send push messages to this app.
After creating an App ID, you should see a list similar to the following:
In the "Apple Push Notification service" column, there are two orange signs that respectively indicate "available for Development" (Development settings) and "Publish able for Production" (publish Production settings ). This means that our App ID can be used for pushing, but we still need to set it. Click the one that says"Configure"To open the page for setting the App ID.
In"Enable for Apple Push Notification service"(Enable the apple Push Service) Click the corresponding "Development Push SSL Certificate"ConfigureButton. The SSL Certificate Assistant Interface of the apple PUSH Service appears:
It requires you to generate a Certificate Signing Request first. We have completed this step. ClickContinue. In the next step, you need to upload the generated Certificate Signing Request (CSR ). Select the CSR file and clickGenerate.
It takes several minutes to generate an SSL certificate. After that, clickContinue.
Click"Download"To download the certificate-the name should be "aps_developer_identity.cer". Click"Done"To close the Assistant Interface and return to the interface for setting the App ID.
As you can see, we now have a valid certificate, you can start to push the certificate to the App. If necessary, you can download the certificate again in the previous place. The development certificate is valid for three months.
When your App is ready for use, repeat the above steps to obtain the certificate used for production. The steps are the same.
Note:The certificate used for production is valid for one year. But you need to update it in advance to ensure that the push service of your App will not be interrupted.
Create a PEM File
Now we have a total of three files:
- CSR
- Private Key (PushChatKey. p12)
- SSL Certificate (aps_developer_identity.cer)
Save the three files. You can choose not to use the CSR file. But when you update the certificate, you can use the same CSR or get a new one. If you get a new CSR, you will also generate a new private key. If the same CSR is used, only the SSL Certificate needs to be changed.
We need to convert the certificate and private key into another more convenient format. The push part of the server is written in PHP, so we can combine the certificate and private key into a PEM file.
It doesn't matter how the PEM file works (I don't know the truth), but it makes it easier for us to use this certificate in PHP. If you want to write this part of the server in other languages, the following steps may not be supported.
We will use the OpengSSL command line tool to complete this task. Open a Terminal and enter the following command.
"Cd" to the folder where you downloaded the certificate and key file. For me, it is the Desktop Folder:
$ cd /Users/matthijs/Desktop
Convert the. cer file to the. pem file:
$ openssl x509 -in aps_developer_identity.cer -inform der -out PushChatCert.pem
Convert the key. p12 file to the. pem file:
$ Openssl pkcs12-nocerts-out PushChatKey. pem-in PushChatKey. p12Enter Import Password:
<输入你导出密钥时用的那个密码>
MAC verified OKEnter PEM pass phrase:
<输入一个新的密码>
Verifying-Enter PEM pass phrase:
<重复密码>
First, you need to enter the password of the. p12 file so that openssl can read the file. Then you need a new password to encrypt the pem file. In this tutorial, I still use "pushchat ". But you should choose a more secure password.
Note: If you do not enter the PEM password, openssl will not give you any error information. But the generated. pem file won't have that key.
Finally, merge the certificate and key into a file:
$ cat PushChatCert.pem PushChatKey.pem > ck.pem
We should test whether the certificate can be used. Run the following command:
$ telnet gateway.sandbox.push.apple.com 2195Trying 17.172.232.226...Connected to gateway.sandbox.push-apple.com.akadns.net.Escape character is '^]'.
We try to establish a general, unencrypted connection with the APNS server. If you see a reply similar to the above, it means that your Mac can be connected to APNS. Press Ctrl + C to disconnect the connection. If you get an error message, make sure that your firewall allows external connection to port 2195.
Let's try again. This time, we will use the SSL Certificate and key to establish an encrypted connection:
$ openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert PushChatCert.pem -key PushChatKey.pemEnter pass phrase for PushChatKey.pem:
You should see a large amount of replies. That is the running information of openssl.
If the connection is successfully established, you can type a few characters. Then, when you press enter, the server will be disconnected from you. If a problem occurs during connection establishment, openssl will provide an error message, but you may need to find the error information in the large information.
It is worth noting that APNS actually has two different servers: The Sandbox server used for testing. Another formal server is used after your program is put into production. We used the server for testing. Because our certificates are used only during development.
Generate Provisioning Profile
We also need to use the Provisioning portal to generate a new Provisioning Profile. Click "Provisioning" in the directory bar on the left and select "Development" to generate a new profile.
Enter the following table:
- Profile Name: PushChat Development
- Certificates: Check your certificate
- App ID: PushChat
- Devices: select your device
We need a new profile because every app with push information needs a profile corresponding to its App ID.
Click Submit to generate your profile. The profile status will start with "Pending ". Refresh the page until it changes to "Active". Then you can download the file (name it PushChat_Development.mobileprovision ).
Double-click the file or drag it to the Xcode icon to add the profile to Xcode.
When you put the program into production, you need to repeat the above steps to generate an Ad Hoc or distribution profile.
A very basic APP
The preparations we have made so far are boring but necessary. We learned in detail the process of generating various certificates because we don't often sit on this issue, but without the push information, it won't work.
By connecting to the sandbox server, we confirmed that the certificate is available. Now let's test whether we can push the prompt information!
Start Xcode and create a new project. Select View-based Application as the template for this project and click Next.
I entered the following spaces:
- Product Name: PushChat
- Company Identifier: com. hollance
- Device Family: iPhone
The Product Name (Product Name) and Company Identifier (Company code) together are Bundle IDs. My name is "com. hollance. PushChat ". You should select the product name and company code (com. yourname. PushChat) corresponding to the App ID you registered on Apple's Provisioning Portal ).
Create a project and open the PushChatAppDelegate. m file. Change didfinishlaunchingwitexceptions to the following:
-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {self. window. rootViewController = self. viewController; [self. window makeKeyAndVisible];// Let the mobile phone know that we want to receive push messages.[[UIApplication sharedApplication] registerForRemoteNotificationTypes :( UIRemoteNotificationTypeBadge | uiremotenotiftypetypesound | uiremotenotiftypetypealert)]; return YES ;} |
We call the registerForRemoteNotificationTypes method to tell the OS that our program wants to receive push information.
Compile and run your program. You should run it on a real apple device because the simulator does not support push messages. Xcode should automatically select the new provisioning profile. If you get an error about "code sign", make sure that you have selected the correct profile. You can modify it in the "Code Sign" Setting section of "build settings.
When you start your program, the system should bring up a selection menu to ask whether the user allows the current program to push the prompt information.
Your program will only ask the user once and remember the user's choice. You can receive push messages only when you select "OK. You can also change the push information settings in the iPhone system settings menu.
The name of your app appears on the prompt setting page of your mobile phone. Here, you can set whether to allow your app to push messages, display the number icon, and send a prompt.
Your app can also use the following code to detect which prompt method the user has enabled:
UIRemoteNotificationType enabledTypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes]; |
To enable our app to receive push notifications, we also need to add the following code to the PushChatAppDelegate. m file:
- (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 a remote push prompt, it will get a device code (device toke ). This is a 32-byte unique number to identify the user's device. You can regard this code as the address of your device. APNS uses this address to push information prompts.
Run your app on the Apple device you used for testing. You should see in the Xcode Console window:
My token is: <740f4707 bebcf74f 9b7c25d4 8e335894 5f6aa01d a5ddb387 462c7eaf 61bb78ad>
The code is an NSDatat object and has a binary data structure. We should not modify it. We only need to know that it has 32 bytes and can be expressed with 64 hexadecimal characters. We will directly use this representation (remove the space between the arc and the center ).
If you run your program in the simulator, didFailToRegisterForRemoteNotificationsWithError: the method should be called because the simulator does not support pushing information prompts.
Our app has been written for the moment. But to start pushing information, we still need to complete the last step!
Push the first message prompt
I once said that you need a server to push information to your app. However, we do not need a server for testing. You can use the following simple PHP script to establish a connection with APNS and push the information to the specified device. You can run this script directly on your Mac.
Download the SimplePush code package and decompress it. You need to modify the simplepush. php file as follows.
// Put your device code here (no space ):$ DeviceToken = 'login ';// Put your key password here:$ Passphrase = 'pushchat ';// Put your prompt information here:$ Message = 'my first push notification! '; |
Copy and paste the device code from the app to the $ deviceToken variable. Make sure that you remove spaces and arc. Set the value of $ passphrase to your password and the value of $ message to the Information string to be pushed.
Copy your ck. pem file to the SimplePush folder. Remember, ck. pem contains your certificate and key.
Open the terminal and enter:
$ php simplepush.php
If everything goes well, the script should respond:
Connected to APNSMessage successfully delivered
After a few seconds, you should receive the first push message prompt of the app:
NOTE: If your app is open, you will not be able to see the push information. This is because we have not written code to receive push information in the app. You should turn off the app and try again.
If simplepush. if the php script exits due to an error, make sure that your PEM file is correctly generated and that you can connect to Apple's sandbox server (refer to the detailed steps above ).
We don't need to rush to know what this script has done, because this is the next part of this tutorial. In the next section, we will learn how to compile a real push server.
What to do next?
So far, your app has been able to receive the push information, and you have successfully pushed the first information with PHP code!
The next step is to take a look at section 2nd of this tutorial. We will learn how to write a simple text message app called PushChat and use the push method to transmit information. We will also learn how to complete a complete Server API and push prompt information in the background!
If you have any questions, comments, and prompts about this tutorial, please join the Forum below for discussion!
This tutorial was written by Matthijs Hollemans, a member of the iOS tutorial team. Matthijs is an experienced free iOS developer who can accept contract work!
Tweet