English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
First, introduction
There are two ways to push messages in iOS, namely local push and remote push. Local push is at https://www.oldtoolbag.com/article/93602.htm this blog has a detailed introduction, here mainly discusses the process and configuration process of remote push.
Second, the principle of remote push mechanism
1Let's start with a very popular chart
When searching for 'iOS remote push', you can always see a flowchart like the following, because this chart is indeed very popular, so I also quote it here:
This diagram illustrates the situation very clearly, the general meaning is as follows: your application server sends messages to Apple's APNS server, the APNS server pushes messages to the specified iPhone, and finally, the iPhone is responsible for pushing the messages to your app. Not to mention how this process is implemented at this point, just looking at this process, you might think that adding Apple's APNS between your server and client would increase the burden on developers. In fact, the opposite is true because of Apple's unified management of push notifications, which makes our work as developers extremely simple.
2How does the server connect to the client?
If you are engaged in Android development, you must be very familiar with long connections and heartbeat packets. In fact, most Android applications implement push notifications through long connections. Due to the openness of the Android system, it is easy for apps to achieve self-startup and background long connections. The heartbeat verification ensures that the long connection remains in an active state, and the server directly pushes messages. If iOS developers also adopt this approach, it would be very difficult. I can only say that it is extremely challenging to keep an app service running without being killed by the system in iOS. Through the above flowchart, comparing with the Android push thinking, we can easily understand that in iOS, there is actually always a long connection, which is the system itself. This long connection is always connected to the APNS server, and then manages the push notifications of all applications centrally.
3What are the advantages of the iOS push mechanism?
These are just some of my personal opinions. There is no inherent good or bad about the system; it all depends on personal preference.
1、Because the push server is the verified user of appleID, the push reliability will be high.
2、All push messages are managed by APNS, which is efficient.
3、Only one long link needs to be maintained on the client side, which saves user traffic consumption and phone performance consumption, and improves security, reducing the probability of malicious push and流氓 software.
Three, in minutes, let your APP receive remote push
1、It is necessary to sharpen the tool before working, so we need to create a push certificate
(1) Request CSR File
Find Keychain Access in the MAC application and open it.
Click the Certificate Assistant in the Keychain Access on the toolbar:
Select to apply for a certificate from the certificate authority:
Fill in the email and name, select save to disk, and then continue.
At this point, the location where we store has such a file: CertificateSigningRequest.certSigningRequest.
(2) Export Key File
Open the Keychain, and you will find a pair of keys with the name you filled in as the common name.
We choose the dedicated key for export and then set a password of our own:
At this time, we have another file with a .p suffix12file.
(3) Create AppId
Go to https://member Center on developer.apple.com:
Log in with your paid developer appleID, and select Certificates:
If your project has already created an APP id, you can create it again, but the APP id you create must support remote push. If you haven't created it yet, click the plus sign to create one:
In the subsequent interface, APP ID has two types: Explicit and Wildcard, which are special and wildcard respectively. Since we need the push function, this ID cannot be wildcard, so we choose the first one.
The Bundle ID that needs to be filled here must be consistent with the one in our App:
In the APP ID service settings, check the Push Notification option, and then click continue.
In minutes, we can handle IOS remote message push
After that, click submit, and finally click Done. At this point, our APP IDs list will show the APP ID we just created.
(4) Create Certificate
Click the APP ID we just created, and you will see a Push Notification line that is not set. Click Edit.
In the Push Notifications settings, the interface is as follows, development is the development certificate, and Production is the product certificate. We need to test now, so we use the Development certificate, and the Production certificate should be used when going live. Click Create Certificate.
Next, click continue, the following interface will prompt us to select a CSR file, the file we created in the first step comes into play here, select that file, and click Generate.
Download the created certificate to the computer:
So far, we have three files, namely CSR file, .p12Files, .cer files. These three files need to be placed in the same directory. The .cer file is divided into test and product versions, and you can choose which one you need. After all this, our preparation work is finally done. Don't be discouraged, in fact, your push work is basically done. It's just that the application process is a bit麻烦,but the code of the project, we almost don't need to configure it.
2Before the troops move, the forage must be prepared——The setting of information push on the server
(1)Process the certificate
Open the terminal and cd to the directory where the three files we obtained above are located.
Execute the following command in the terminal:
$ openssl x509 -in aps_development.cer -inform der -out PushCert.pem
aps_development.cer is the filename of the .cer file generated just now. A pem file will be generated in the current folder, which is the corresponding certificate for our server.
Then execute the following command again:
$ openssl pkcs12 -nocerts -out PushKey.pem -in key.p12
key.p12Is the .p generated above12The filename of the file. At this time, the terminal will prompt you to enter a password, which is the password we set for the key above. After entering the password and pressing Enter, if the password is correct, it will prompt us to enter a new password (be sure to remember it), enter it twice, and the terminal will prompt that the PushKey.pem file has been successfully created.
The last step is to combine the two pem files we generated into one:
$ cat PushCert.pem PushKey.pem > ck.pem
(2)Test whether the certificate is available
Execute the following command in the terminal:
$ telnet gateway.sandbox.push.apple.com 2195
Wait a moment, if the terminal displays the following situation, the certificate is normal.
Then execute the following command:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert PushChatCert.pem -key PushKey.pem
After entering the password and pressing Enter, the following result is displayed, indicating a successful connection:
3Endless天涯海角,一步之遥——Application configuration in the application
Add the following code to our project's AppDelegate:
- (BOOL)application:(UIApplication *} *} double version = [[UIDevice currentDevice].systemVersion doubleValue];//Determine system version. if(version>=8.0f){ UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert) categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; } UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound; [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes]; } } - (void)application:(UIApplication *application didReceiveRemoteNotification:(NSDictionary *userInfo{ // Handle push message NSLog(@"userinfo:%@", userInfo); NSLog(@"Received push message:%@", [[userInfo objectForKey:@"aps"] objectForKey:@"alert"])); } - (void)application:(UIApplication *application didFailToRegisterForRemoteNotificationsWithError:(NSError *) error {}} NSLog(@"Registfail%@",error); } -(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ NSLog(@"%@",deviceToken);//这里的Token就是我们设备要告诉服务端的Token码 }
以下是网上搜索到的PHP服务端代码:
<?php //这里填写设备的Token码 $deviceToken = '74314cc9e8f747e2fa96c2c1585c830cdf994de6b453ce9fa1c09ba396b2f9e9; //这里是密钥密码 $passphrase = 'abcabc'; //推送的消息 $message = '这是一条推送消息'; //////////////////////////////////////////////////////////////////////////////// $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');//ck文件 stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // 打开与APNS服务器的连接 $fp = stream_socket_client( 'ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL); echo 'Connected to APNS' . PHP_EOL; // 创建有效载荷主体 $body['aps'] = array( 'alert' => $message, 'sound' => 'default' ); // 将有效载荷编码为JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) echo 'Message not delivered' . PHP_EOL; else echo 'Message successfully delivered' . PHP_EOL; // Close the connection to the server fclose($fp); ?>
Place the above PHP file and our ck file in the same directory. Execute the following command in the current directory of the terminal:
$php push.php
If our device strategy is normal, we can receive push messages:
4. Points to Note
1If there is an error such as 'key cannot be accessed' when the terminal sends information, please check if you have cd to the current directory. If there are still problems, regenerate the key part once.
2Please note that the characters in the PHP code are English characters.
This article has been organized into 'iOS Push Tutorial', welcome to learn and read.
That's all for the content of this article. Hope it helps everyone's learning and also hope everyone will support the Yelling Tutorial.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.