IOS network push notification
Push notifications are initiated by application service providers and sent to the application client through Apple's APNs (Apple Push Notification Server.
The process of pushing notifications can be divided into the following steps:
The application service provider sends the message and device token to Apple's APNs server from the server side.
APNs searches for the corresponding device on the registered device (iPhone, iPad, iTouch, mac, etc.) based on the device token and sends the message to the corresponding device.
The client device sends the received message to the corresponding application, and the application pops up the notification message according to the user settings.
1. The application registers APNs to push messages.
Note:
A. only registered applications can receive messages. Generally, the program uses registerUserNotificationSettings of the UIApplication to register a message. The method for notifying registration in ios8, for iOS 7 and earlier versions, refer to other code.
B. there are two prerequisites before registration: The Development configuration file (provisioning profile, that is. the App ID cannot use the wildcard ID. You must use the specified app id and select the Push Notifications service in the generated configuration file. The general development configuration file cannot be registered; the Bundle Identifier of the application must be exactly the same as the app id used to generate the configuration file.
2. iOS receives device tokens from APNs and obtains device tokens in the application.
Note:
A. Obtain the token in the-(void) application :( UIApplication *) application didRegisterForRemoteNotificationsWithDeviceToken :( NSData *) deviceToken proxy method of the UIApplication. This method occurs after registration.
B. if the device token cannot be obtained correctly, you can view the detailed error information in the-(void) application :( UIApplication *) application didfailtoregisterforremotenotifswitherror :( NSError *) error proxy method of the UIApplication, this method occurs after the device token fails to be obtained.
C. The simulator cannot obtain the device token because it must be debugged by a real machine.
3. the iOS app sends the device token to the application provider and notifies the server that the current device allows messages to be received.
Note:
A. the device token Generation Algorithm is only available to Apple. To ensure that the algorithm can still normally receive notifications sent by the server after the algorithm changes, the device token is retrieved every time the application starts. (Note: the acquisition of device token will not cause performance problems. Apple has made optimizations ).
B. generally, you can create a network connection and send it to the server of the application provider. In this process, you can store the device token obtained last time to avoid repeated sending, once the device token has changed, it is best to send the original device token to the server. The server deletes the new token to prevent the server from sending invalid messages.
4. On the server side, the application provider sends the device token information sent to APNs
Note:
A. Specify device tokens and message content when sending the message, and organize the message content completely according to the official message format of Apple. Generally, other third-party message push frameworks can be used.
5. APNs searches for registered device push messages based on the device token in the message.
Note:
A. under normal circumstances, messages can be successfully pushed to the client device based on the device token, but it does not rule out that the user uninstalls the program. In this case, the message fails to be pushed, APNs notifies the server of this error message to avoid resource waste (the server can delete the device tokens that have been stored based on the error and will not send them again ).
# Import "AppDelegate. h"
# Import "KCMainViewController. h"
@ Interface AppDelegate ()
@ End
@ Implementation AppDelegate
# Pragma mark-application proxy method
# After The pragma mark application is started
-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {
_ Window = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen]. bounds];
_ Window. backgroundColor = [UIColor colorWithRed: 249/255. 0 green: 249/255. 0 blue: 249/255. 0 alpha: 1];
// Set the global navigation bar style and color
[[UINavigationBar appearance] setBarTintColor: [UIColor colorWithRed: 23/255. 0 green: 180/255. 0 blue: 237/255. 0 alpha: 1];
[[UINavigationBar appearance] setBarStyle: UIBarStyleBlack];
KCMainViewController * mainController = [[KCMainViewController alloc] init];
_ Window. rootViewController = mainController;
[_ Window makeKeyAndVisible];
// Register the push notification (note that the iOS8 registration method has changed)
[Application registerUserNotificationSettings: [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories: nil];
[Application registerForRemoteNotifications];
Return YES;
}
# After The pragma mark registers the push notification
// Receive the device token here
-(Void) application :( UIApplication *) application didRegisterForRemoteNotificationsWithDeviceToken :( NSData *) deviceToken {
[Self addDeviceToken: deviceToken];
NSLog (@ "device token: % @", deviceToken );
}
# After The pragma mark fails to get the device token
-(Void) application :( UIApplication *) application didFailToRegisterForRemoteNotificationsWithError :( NSError *) error {
NSLog (@ "didFailToRegisterForRemoteNotificationsWithError: % @", error. localizedDescription );
[Self addDeviceToken: nil];
}
# After The pragma mark receives the push notification
-(Void) application :( UIApplication *) application didReceiveRemoteNotification :( NSDictionary *) userInfo {
NSLog (@ "receiveRemoteNotification, userInfo is % @", userInfo );
}
# Pragma mark-Private Method
/**
* Add the device token to the server.
*
* @ Param deviceToken device token
*/
-(Void) addDeviceToken :( NSData *) deviceToken {
NSString * key = @ "DeviceToken ";
NSData * oldToken = [[NSUserDefaults standardUserDefaults] objectForKey: key];
// If the token in the preference settings is different from the token obtained by the new device, the new token is stored and sent to the server.
If (! [OldToken isEqualToData: deviceToken]) {
[[NSUserDefaults standardUserDefaults] setObject: deviceToken forKey: key];
[Self sendDeviceTokenWidthOldDeviceToken: oldToken newDeviceToken: deviceToken];
}
}
-(Void) sendDeviceTokenWidthOldDeviceToken :( NSData *) oldToken newDeviceToken :( NSData *) newToken {
// Make sure that the real machine can access the following address normally.
NSString * urlStr = @ "http: // 192.168.1.101/RegisterDeviceToken. aspx ";
UrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURL * url = [NSURL URLWithString: urlStr];
NSMutableURLRequest * requestM = [NSMutableURLRequest requestWithURL: url cachePolicy: 0 timeoutInterval: 10.0];
[RequestM setHTTPMethod: @ "POST"];
NSString * bodyStr = [NSString stringWithFormat: @ "oldToken =%@ & newToken =%@", oldToken, newToken];
NSData * body = [bodyStr dataUsingEncoding: NSUTF8StringEncoding];
[RequestM setHTTPBody: body];
NSURLSession * session = [NSURLSession sharedSession];
NSURLSessionDataTask * dataTask = [session dataTaskWithRequest: requestM completionHandler: ^ (NSData * data, NSURLResponse * response, NSError * error ){
If (error ){
NSLog (@ "Send failure, error is: % @", error. localizedDescription );
} Else {
NSLog (@ "Send Success! ");
}
}];
[DataTask resume];
}
@ End
Certificate
Common certificates for iOS include development certificates and publishing certificates. These two certificates are required, both for debugging on a real machine and for publishing applications to the App Store. They are the basic certificates for iOS development.
A. Development Certificate: development certificate can be classified into general development certificate and push certificate. If it is only a general application, the former can be satisfied, but if it is a development push application, the push certificate must be used.
B. Publish a certificate: The certificate can be divided into general publish certificate, push certificate, Pass Type ID certificate, site publish certificate, VoIP service certificate, and Apple Pay certificate. Similarly, for applications that require special services, You must select the corresponding certificate.
Application ID
App ID, the unique Identifier of the App, corresponds to the Bundle Identifier of the iOS App. App IDs are divided into wildcard App IDs and specific App IDs in the Apple Developer Center. The former is generally used for general application development, one ID can be applied to multiple applications with different identifiers. However, an Application ID must be specified for applications that use services such as message push, Passbook, site publishing, and iCloud.
Device ID
The identifier used to identify each hardware device. Note that it is not a device token. device token is a set of identifiers generated based on the UDID using an algorithm that only Apple knows.
Configuration Overview
Provisioning Profiles, also known as PP files. The configuration files that package UDID, App ID, and development certificate are also divided into development and release configuration files.
Key
When applying for a development certificate, you must first submit a key request file. For the mac that generates the key request file, you only need to download the certificate and configuration introduction for development. However, if you want to develop on other machines, you must export the secret key in the certificate (A. p12 file after export) and then import it to other machines. In addition, if an application on the push server needs to send messages to APNs, The. p12 key file must also be used, and the key file must be the corresponding key exported from the push certificate.
Supplement-notification center
For many beginners, the concept of local notifications, push notifications, and iOS notification centers in iOS is often mixed. In fact, there is no relationship between the two. In fact, they do not belong to a framework. The former belongs to the UIKit framework, and the latter belongs to the Foundation framework.
The notification center is actually a message broadcast mechanism within the iOS program. It is designed to solve the decoupling between different objects in the application. It is designed based on the observer mode and cannot communicate across application processes. When the notification center receives a message, it sends the message to the subscriber based on the internal message forwarding table.