Transfer from Feng Junwen's blog
Apple controls the device very strictly, and the process of message push must be APNs
Push mechanism of APNs
Unlike our own push service on Android, Apple controls the device very strictly, and the process of message push must be APNs:
Here Provider refers to an application's developer, of course, if the developer uses AVOs cloud services, the request to send messages to us, then the Provider here is AVOs Cloud push service program. Can be divided into three steps:
The first step: AVOs Cloud push service program to send messages, the purpose of the device's unique identity package, to APNs.
Step two: APNs in its list of applications for the registered push service, find the device with the appropriate identity and send the message to the device.
The third step: The iOS system sends the message to the appropriate application, and follows the settings to eject the push notification
To achieve message push, there are two important points:
1,app's Push Certificate
To be able to fully implement a message push, we need to open the push notifications in the app ID, we need to prepare provisioning profile and SSL certificate, And be sure to note that development and distribution environments need to be separated. Finally, import the SSL certificate into the AVOs cloud platform and try to push the remote message. Specific operating procedures can be found in our User guide: iOS push certificate Setup Guide.
2, device identification Devicetoken
Knowing who to push, or which app to push to, APNs also needs to know which device to push to, which is what device identification does. The process for obtaining the device identity is as follows:
The first step: The app opens the push switch, the user wants to confirm TA wants to obtain the push message of the app
Step two: App gets a Devicetoken
The third step: The app will save Devicetoken, here is to [AVInstallation saveInBackground] save Devicetoken to AVOs Cloud.
Fourth step: When a specific event occurs, the developer delegates AVOs Cloud to send a push message, AVOs Cloud's push server sends a push message to APNs, APNs the last message to the user device
Several concepts related to push delivery
Message type
A message is pushed over and can be expressed in the following ways:
1. Display a alert or banner to show specific content
2. Prompt for a new message number on the app icon
3. Play a sound
Developers can set up each time they push, and developers can choose different ways to prompt them when they are pushed to the user's device.
Local message notification
There are two kinds of message notifications on iOS, one for local Notification and one for remote messages (Push Notification, also known as Remote Notification), designed both to alert users Now something new has happened that will entice the user to reopen the app.
When is local news useful? For example, if you are doing a to-do tool application, there will be a point in time for each item that the user joins, and the user can ask the To-do app to remind Ta at a certain point in time before the event expires. To achieve this, the app can dispatch a local notification to send an alert message or other hint after the time point is reached.
When we are dealing with push messages, we can also use these two methods in a comprehensive manner.
How to implement push in code
First, we want to get devicetoken.
The app needs to register for remote notifications every time it starts--by calling the UIApplication的registerForRemoteNotificationTypes: method, passing it to the message type parameters that you want to support, such as:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // do some initiale working ... [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound]; return
If the registration is successful, the Token,ios system that APNs will return to your device will pass it to the app delegate agent
application:didRegisterForRemoteNotificationsWithDeviceToken:
method, you should save the token to the AVOs cloud backend in this method, for example:
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSLog(@"Receive DeviceToken: %@", deviceToken); AVInstallation *currentInstallation = [AVInstallation currentInstallation]; [currentInstallation setDeviceTokenFromData:deviceToken]; [currentInstallation saveInBackground]; }
If registration fails
application:didFailToRegisterForRemoteNotificationsWithError:Method is called, you can see the specific error message through the Nserror parameter, for example:
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSLog(@"注册失败,无法获取设备ID, 具体错误: %@", error); }
Note: The registration process needs to be invoked every time the app is launched, which does not pose an additional burden because the iOS operating system is cached locally after the first valid device token, and is returned immediately after the app is called, registerForRemoteNotificationTypes: and no further network requests are made. In addition, the app layer should not cache device tokens because device tokens can also change-if the user re-installed the operating system, then the device token given by APNs will be different from the previous one, or, The user restore the original backup to the new device, then the original devices token will also expire.
Second, we're going to handle the callback after the message is received.
We can imagine several usage scenarios for message notifications:
1, when the app has not been launched, received a message notification. The operating system then displays an alert message by default, marking a number on the app icon and even playing a sound.
2, after the user sees the message, click on the Action button or click on the app icon. If the action button is clicked, the system will call the
application:didFinishLaunchingWithOptions:This proxy method is used to launch the application, and the notification payload data is passed in. If the app icon is clicked, the system will call application:didFinishLaunchingWithOptions: this proxy method to launch the application, the only difference is that there will be no notification information in the startup parameters.
The sample code is as follows:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // do initializing works ... if (launchOptions) { else ... [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions]; } [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound]; return
3, what happens when the app is running when the remote message is sent over?
The method of the app proxy is application:didReceiveRemoteNotification: called, and the payload data in the remote message is passed in as a parameter.
The sample code is as follows:
- (void) Application: (uiapplication*) Application Didreceiveremotenotification: (nsdictionary*) UserInfo {if(Application. ApplicationState= = uiapplicationstateactive) {//Convert to a local notification, display to the notification bar, you can also directly display a alertview, just that slightly aggressive:) uilocalnotification*localnotification = [[uilocalnotificationALLOC] init]; Localnotification. UserInfo= UserInfo; Localnotification. Soundname= Uilocalnotificationdefaultsoundname; Localnotification. Alertbody= [[UserInfo objectforkey:@"APS"] objectforkey:@"Alert"]; Localnotification. Firedate= [NSDateDate]; [[uiapplicationSharedapplication] schedulelocalnotification:localnotification]; }Else{[Avanalytics trackappopenedwithremotenotificationpayload:userinfo]; } }
FAQs FAQ
1. Can I send long messages?
No, APNs limits the maximum length of payload per notification to 256 bytes, and the extra-long message cannot be sent.
2. How do I add a sound reminder to my push?
A message push is a sound that can be specified. For example, you can use a cheerful voice for positive feedback, and a low-pitched sound for negative feedback, all of which can be used to make a person's eyes shine.
You need to put some AIFF, WAV, or CAF audio files into the app's resource file, and then specify a different audio file name when you push.
3. What is the badge of the push?
Push does not necessarily cause the red number on the app icon to increase, and whether or not to display this number, depends on the developer himself.
When sending a push message, we can choose whether or not to increment this number, and if you do not select this item, then the message push does not cause the red number on the app icon to appear.
OK, now the question is coming, if this number is out, how can we let it go away?
Actually we just need to set it at any time
UIApplication.applicationIconBadgeNumberA property of 0 allows this number to disappear.
In general we will choose when the application starts
( application:didFinishLaunchingWithOptions: in the method), or simply, every time the application is switched to the foreground (Applicationwillenterforeground: method), call this line of code, you can immediately clear out the badge number.
- What is the notification format that AVOs cloud platform sends out?
For each push message, there is a payload, usually composed of a JSON dictionary, which is essential is the APS property, which corresponds to the value of a dictionary, contains the following:
1) Alert message (text or dictionary)
2) Apply the red number on the icon
3) sound file name to play
In an app opened by push activation,
application:didFinishLaunchingWithOptions:The options parameter is the big Dictionary object.
{ aps = { "hello, everyone"; 2; default;
Notice here that the value of the alert section can be either a string (text message) or a JSON dictionary. When it is a text message, the system will display the text in a alertview, if it is also composed of a JSON dictionary, its format is as follows:
* Body
* Action-loc-key
* Loc-key
* Loc-args
* Launch-image
The body part is the text message that will be displayed in Alertview, the Loc-property is mainly used to implement localization message, Launch-image is just the name of an image file in the main bundle of the app, in general we do not specify this attribute.
How to display localized messages
There are two ways to localize a push message:
1) in the push payload using Loc-key and Loc-args to specify localization, so that the provider party only need to follow the unified format to send, the message parsing and assembly is done by the client.
2) If the push payload contains no Loc-key/loc-args information, then the provider party needs to do local processing, and then send different messages to different device, in order to do this, but also need the app to upload device Token when the user's language settings are also transmitted back.
At present, because AVOs cloud is mainly aimed at Chinese mainland market and overseas Chinese users, so we do not provide multi-lingual support on the push.
How the app responds to push messages
The process described above can only be a simple display of remote messages, activating the user to get them back to the app. But sometimes we want to give users a better experience, such as if we tell the user: Zhang San just commented on your photo. At this time, if the user clicks the action button to enter the app, do we show the specific comment page as well, or display the usual launch page and let the user find Zhang San's comments on their own? I think responsible developers will choose the former.
To be flexible in responding to different types of notification messages, we need to add more information to the payload of the notification, rather than just the text message with alert. For the AVOs cloud messaging push platform, developers are required to use the JSON format for more advanced features. For example, if we send such a JSON string, we {"action":{"type":4},"alert":"hello, everyone”} will eventually receive such a UserInfo Dictionary in the app:
{ action = { type4; }; aps = { "hello, everyone"; 4;
"Hello, everyone" will show up in Alertview, but the whole dictionary will be passed launchoptions to the application: didFinishLaunchingWithOptions: method, so we can implement different jumps for different messages within the program.
IOS Detail Message Push