English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of Local Push and Remote Push in iOS

First, introduction

Divided into local push and remote push2types. They can prompt users even when the application is not open or the phone is locked. They all need to be registered. After registration, the system will pop up a prompt box (as shown in the figure below) to prompt the user whether to agree. If agreed, use it normally; if the user does not agree, the prompt box will not pop up when the program is opened next time, and the user needs to go to the settings to set it. There are a total of three types of prompts:

UIUserNotificationTypeBadge:Information prompt at the top right corner of the application icon

UIUserNotificationTypeSound:Play a prompt sound

UIUserNotificationTypeAlert:Prompt box

Second, local push

1 Registration and handling

The code is as follows:

 /// Generally register notifications at startup, and call this program after the program is killed, and after clicking the notification
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) { // iOS8
 UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];
 [application registerUserNotificationSettings:setting];
 }
 if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]) {
 // Here add handling code
 }
 return YES;
}
/// The program has not been killed (in the foreground or background), and the program will be called after clicking the notification
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
 // Here add handling code
}

As can be seen, there are two methods for handling the code, one is

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;
The other one is
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;

If the program has not been killed, that is, it is in the foreground or background, then call the former; if the program is killed, then call the latter.

2 Send notification

The code is as follows

- (IBAction)addLocalNotification {
 // 1.create a local notification
 UILocalNotification *localNote = [[UILocalNotification alloc] init];
 // 1.1. Set the time when the notification is sent
 localNote.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
 // 1.2. Set the notification content
 localNote.alertBody = @"This is a pushThis is a push";
 // 1.3. Set a text displayed below the font when the screen is locked
 localNote.alertAction = @"Hurry!!!!!";
 localNote.hasAction = YES;
 // 1.4. Set the launch image (through the notification opened)
 localNote.alertLaunchImage = @"../Documents/IMG_0024.jpg";
 // 1.5. Set the incoming sound
 localNote.soundName = UILocalNotificationDefaultSoundName;
 // 1.6. Set the number displayed in the upper left corner of the application icon
 localNote.applicationIconBadgeNumber = 999;
 // 1.7. Set some additional information
 localNote.userInfo = @{@"qq" : @"704711253", @"msg" : @"success"};
 // 2. Execute notification
 [[UIApplication sharedApplication] scheduleLocalNotification:localNote];
}

The effect is as follows:

3 Cancel notification

// Cancel all local notifications
[application cancelAllLocalNotifications];

3. Remote Push

Different from the push service we implement on Android, Apple has very strict control over devices, and the message push process must go through APNs (Apple Push Notification service).

Generally, if a program is running in the background and cannot execute code (Audio, VoIP, etc. can run in the background), or if the program exits, it will disconnect from the corresponding application's background server, and will not receive information sent by the server. However, as long as each device is connected to the internet, it will establish a long connection (persistent IP connection) with Apple's APNs server. This way, our own server can indirectly maintain a connection with the device through Apple's APNs server. The illustration is as follows:

Steps to Use:

1 Select Backgroud Modes -> Remote notifications, mainly for iOS7After that, Apple supports background execution, if you open it here, when receiving remote push notifications, the program can also perform some processing in the background, as shown in the figure below:

2 The registration of remote push notifications is different from local push notifications, iOS8.0 before and after are also different, see the code below.

In addition, when using push notifications for the first time, there may be such a question: didFinishLaunchingWithOptions is called every time the program is opened, does this mean that the registration function is called every time, and the pop-up window asking the user 'whether to allow push notifications' is displayed every time? In fact, this window will only pop up once when the program is opened for the first time, regardless of whether the user allows or not, Apple will remember the user's choice, and multiple calls to the registration function have no effect on the user

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 // iOS8Distinguish between after and before
 if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
 UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];
 [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
 }
 [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIUserNotificationTypeSound];
 }
 return YES;
}
/// The significance of this function is that when the user turns off notifications in the settings, this function is called when the program starts, and we can obtain the user's settings
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
 [application registerForRemoteNotifications];
}

3 If the registration fails, for example, due to lack of certificates, etc., it will call: }}

/// Call when registration fails
- (void)application:(UIApplication *error { *error {
 NSLog(@"Remote notification registration failed: %@",error);
}

4 Obtain deviceToken

If the user agrees, Apple will generate the deviceToken based on the application's bundleID and the phone's UDID, and then call the application's didregister method to return the devicetoken. The program should send the devicetoken to the server of the application. It is the server's obligation to store it (if multiple logins are allowed, it may store multiple devicetokens). The deviceToken may also change: "If the user restores backup data to a new device or computer, or reinstalls the operating system, the device token changes", so it should be sent to the server (provider) every time

/// After the user agrees, this program will be called to obtain the system's deviceToken, and the deviceToken should be sent to the server for storage. This function will be called every time the program starts (on the premise that the user allows notifications)
- (void)application:(UIApplication *deviceToken { *deviceToken {
 NSLog(@"deviceToken = %@",deviceToken);
}

5 when the user clicks on the notification

the program will open by default. There are three functions for handling code, divided into iOS7before and after, and whether the program is in the background

5.1 iOS7and after that

This function will be called regardless of whether the program is killed or in the background, as long as the user clicks on the notification, so if it is iOS7If so, there is no need to handle it in didFinishLaunchingWithOptions; just handle it in the following function. Avoid duplicate handling in the didFinishLaunchingWithOptions function at this time.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
 // userInfo
} 

Note: When enabling background execution in the first step, if the user does not click on the notification, the following can also be executed:

 - (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo fetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler 

5.2 iOS7Before

After the user clicks on the notification, if the app is killed, the first function below will be called, and if the app is in the background, the second function below will be called, so the two functions should be used together

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 // Get remote push messages
 NSDictionary *userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
 if (userInfo) {
 // There are push messages, handle push messages
 }
 return YES;
}
/// iOS3Only after that, only when the app is in the background and the user clicks on the notification, will it be called, which should be used with didFinishLaunchingWithOptions
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
 // userInfo
}

In actual programming, if you want to be compatible with iOS7Previously, the three functions could be used simultaneously, all listed, and the system would automatically select the appropriate call.

6 Summarize the function calls:

After the first installation and launch:

didRegisterForRemoteNotificationsWithDeviceToken was called

The system asks the user whether they agree to receive Notifications

Regardless of whether the user agrees or refuses, didRegisterUserNotificationSettings was called

When the app is not launched for the first time:

If notifications are in the denied state: didRegisterUserNotificationSettings was called

If notifications are in the allowed state

didRegisterForRemoteNotificationsWithDeviceToken was called

didRegisterUserNotificationSettings is called

User modifies notifications settings during the application runs:

From denied to allowed: didRegisterForRemoteNotificationsWithDeviceToken is called

From allowed to denied: nothing happens

7 Server-side push format

{
 "aps" : {   // There must be
 "alert" : "string",
 "body" : "string",
 "badge" : number,
 "sound" : "string"
 },
 "NotiId" : 20150821, // Custom key value
}

8 Push size limit

The size of the push notification varies according to the API used by the server. When using HTTP/2 When using the provider API, the maximum load is4kB; when using legacy binary interface, the maximum load is2kB. When the load size exceeds the specified load size, APNs will refuse to send this notification.

9 The overall is as shown in the figure below (taking WeChat push as an example):

10 Finally, you still need to apply for a certificate, and will not be elaborated here-_-

This article has been organized into 'iOS Push Tutorial', welcome to learn and read.

That's all for this article, I hope it will be helpful to everyone's study, and I also hope everyone will support the Yelling Tutorial more.

Statement: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, does not undergo人工 editing, nor assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting. Provide relevant evidence, and once verified, this site will immediately delete the suspected infringing content.)

You May Also Like