Reprint Address: https://www.hybunion.cn/downloadyinshang.html
After a lot of students ask us, iOS push on how to do ah, why my equipment is always not receive push, here with you focus on the implementation of iOS push on the details. the push mechanism of APNs
Unlike Android's own implementation of the push service, Apple has a very strict control over the device, and the message push process has to go through APNs:
Here Provider refers to an application of the developer, of course, if developers use AVOs cloud service, the request to send a message to us, then the Provider here is AVOs cloud of the push service program. The diagram above can be divided into three steps:
The first step: AVOs Cloud push Service program to send the message, the purpose of the device's unique identification package, sent to APNs.
Step two: APNs in its own registered push Service Application list, find the device with the appropriate identity, and send the message to the device.
Step three: The iOS system sends the message to the appropriate application and pops the push notice as set
In order to implement 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, which requires us to prepare the provisioning profile and SSL certificate, and must pay attention to development and distribution environment is need to separate. Finally, the SSL certificate is imported into the AVOs cloud platform to try remote message push. Specific procedures can refer to our guide to use: iOS Push Certificate Setup Guide.
2, equipment identification Devicetoken
Knowing who to push, or to which app to push, APNs also needs to know which device to push, which is the role of device identification. The process for obtaining device identities is as follows:
Step one: App opens push switch, user wants to confirm TA want to get the app's push message
Step two: App gets a Devicetoken
Step three: App will save the Devicetoken, this is through [avinstallation Saveinbackground] to save Devicetoken to AVOs Cloud
Fourth step: When certain events occur, the developer entrusts AVOs Cloud to send the push message, at this time AVOs Cloud's push server will send a push message to APNs, APNs the last message to the user device push related several concept message types
A message is pushed over, there are several forms of expression:
Display an alert or banner to show specific content
Tip A new to message number on the application icon
Play a piece of sound
Developers can set up every push, and developers can choose different cues when pushing to a user device. Local Message Notification
There are two kinds of message notifications on iOS, one is the local message (locally Notification), the other is a remote message (Push Notification, also known as Remote Notification), both of which are designed to alert the user, Now something new is happening that attracts users to reopen apps.
When is the local message useful? For example, you are working on a to-do tool class application that will have a complete point in time for every item that the user joins, and the user can ask the to-do to remind Ta at a point in time before the event expires. To do this, the app can dispatch a local notification, sending an alert message or other prompts after the point of time.
When dealing with push messages, we can use these two methods in combination. how to implement push in code first, we want to get devicetoken.
The app needs to register a remote notification every time it starts-by calling UIApplication's Registerforremotenotificationtypes: method, passing it to the message type parameters you want to support, such as:
-(BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) launchOptions
{
// do some initiale working
...
[application registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
return YES;
}
If the registration is successful, APNs will return the token to your device, and the iOS system will pass it to the app delegate agent-application: didRegisterForRemoteNotificationsWithDeviceToken: method, you should save the token to the AVOS Cloud background 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 the registration fails, the application: didFailToRegisterForRemoteNotificationsWithError: method will be called, you can see the specific error message through the NSError parameter, for example:
-(void) application: (UIApplication *) application didFailToRegisterForRemoteNotificationsWithError: (NSError *) error {
NSLog (@ "Registration failed, unable to get device ID, specific error:% @", error);
}
Please note that the registration process needs to be called every time the app starts, which does not bring additional burden, because the iOS operating system will cache it locally after obtaining the valid device token for the first time, and then call the app later When registerForRemoteNotificationTypes: will return immediately, no network request will be made. In addition, the device token should not be cached because the device token may also change-if the user reinstalls the operating system, the device token given by APNs will be different from the previous one, or the user will restore After the original backup is added to the new device, the original device token will also be invalid. Second, we have to handle the callback after receiving the message
We can imagine several usage scenarios for message notification:
1. When the app is not started, a message notification is received. At this time, the operating system will display an alert message in the default way, mark a number on the app icon, or even play a sound.
2. After seeing the message, the user clicks the action button or clicks the application icon
If the action button is clicked, the system will start the application by calling application: didFinishLaunchingWithOptions: this proxy method, and will pass the notification payload data into it.
If the application icon is clicked, the system will also call application: didFinishLaunchingWithOptions: this proxy method to start the application, the only difference is that there will be no notification information in the startup parameters at this time.
The sample code is as follows:
-(BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) launchOptions
{
// do initializing works
...
if (launchOptions) {
// do something else
...
[AVAnalytics trackAppOpenedWithLaunchOptions: launchOptions];
}
[application registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
return YES;
}
3. If the app is running when the remote message is sent, what will happen at this time?
The application: didReceiveRemoteNotification: method of the app agent will be called, and the payload data in the remote message will be passed in as a parameter.
The sample code is as follows:
-(void) application: (UIApplication *) application didReceiveRemoteNotification: (NSDictionary *) userInfo {
if (application.applicationState == UIApplicationStateActive) {
// Converted to a local notification, displayed in the notification bar, you can also directly display an alertView, just that a little aggressive :)
UILocalNotification * localNotification = [[UILocalNotification alloc] init];
localNotification.userInfo = userInfo;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = [[userInfo objectForKey: @ "aps"] objectForKey: @ "alert"];
localNotification.fireDate = [NSDate date];
[[UIApplication sharedApplication] scheduleLocalNotification: localNotification];
} else {
[AVAnalytics trackAppOpenedWithRemoteNotificationPayload: userInfo];
}
}
Frequently Asked Questions FAQ Can I push long messages
No, APNs limits the maximum length of each notification's payload to 256 bytes, and ultra-long messages cannot be sent. How to add sound reminder
Message push can specify the sound. For example, you can use a cheerful voice for positive feedback and a lower voice for negative feedback, which can achieve the purpose of ingenuity.
You need to first put some aiff, wav or caf audio files into the app's resource files, and then specify a different audio file name when pushing.
IOS push detail 1 (reproduced) __ IOS push Badge is going on
Pushing does not necessarily cause the red number on the application icon to increase. Whether or not this number is displayed depends on the developer himself.
When sending a push message, we can choose whether to increment this number; if this item is not selected, then the message push will not cause the red number on the application icon to appear.
IOS push detail 1 (reproduced) __IOS
Ok, now the question is coming, if this number is made, how can it disappear.
In fact, we only need to set the UIApplication.applicationIconBadgeNumber property to 0 at any time to make this number disappear.
Generally, we will choose to start the application (application: didFinishLaunchingWithOptions: method), or simply, every time the application is switched to the foreground (applicationWillEnterForeground: method), call this line of code, you can immediately clear Badge The numbers are gone. What is the format of the notification sent by the AVOS Cloud platform?
For each push message, it contains a payload, usually composed of a JSON Dictionary, which is indispensable is the aps attribute, and its corresponding value is also a Dictionary, including the following content:
alert message (text or Dictionary)
Red numbers on application icons
Play sound file name
In the open event of an app activated by push, the options parameter of application: didFinishLaunchingWithOptions: is this large Dictionary object.
{
aps = {
alert = "hello, everyone";
badge = 2;
sound = default;
};
}
Note the alert part here. Its value can be a String (text message) or a JSON Dictionary. When it is a text message, the system will display the text in an alertview; if it is also composed of a JSON Dictionary, the format is as follows:
body
action-loc-key
loc-key
loc-args
launch-image
The body part is the text message to be displayed in the alertView. The loc- attribute is mainly used to implement localized messages. The launch-image is just the name of an image file in the main bundle of the app. Generally, we do not specify this attribute. How to display localized messages
There are two ways to localize push messages:
1. Use loc-key and loc-args in the pushed payload to specify localization, so that the provider only needs to send in a unified format, and the client parses and assembles the message.
2. If the pushed payload does not contain loc-key / loc-args information, then the provider needs to do localization and send different messages to different devices. In order to do this, the app needs to upload The device token also sends back the user's language setting information.
At present, because AVOS Cloud is mainly aimed at the Chinese mainland market and overseas Chinese users, we do not provide multi-language support on push. How should the application respond to push messages
The processing flow mentioned above can only simply show the remote message and activate the user to let them return to the app. But sometimes, we hope to bring users a better user experience, for example, if we tell users: Zhang San just commented on your photos. At this time, if the user clicks the action button to enter the app, should we show the specific comment page, or show the usual startup page and let the user find Zhang San's comment? I think responsible developers will choose the former :)
In order to respond flexibly to different types of notification messages, we need to add more information to the notification payload, not just the text information from the alert. For the AVOS Cloud message push platform, developers need to use the JSON format with more advanced functions. For example, we send Such json string
{"action": {"type": 4}, "alert": "hello, everyone"} Eventually you will receive this UserInfo Dictionary in the app:
{
action = {
type = 4;
};
aps = {
alert = "hello, everyone";
badge = 4;
};
}
"Hello, everyone" will be displayed in the alertView, but the entire Dictionary will be passed to the application: didFinishLaunchingWithOptions: method through launchOptions, so that we can achieve different jumps to different messages in the program.