ios-local push and remote push, common three-party push and common test methods, push the implementation and the rationale of the detailed (reprinted from Xue Silver 492199045@qq.com)

Source: Internet
Author: User

What is message push

To give a common example, our mobile phone often pop up some information, such as QQ information, information, and so on, this is the common message push.

For example:

Type of message push:
    • Display a banner at the top of the screen (show specific content)
    • Pop up a uialertview in the middle of the screen (show specific content)
    • Display a banner on the lock screen (lock screen status, display specific content)
    • Update the number of app icons (indicating the number of new content)
    • Play Sound (Reminder)

This is the style of our common push message, and we can customize how the received message is displayed on the phone.

In some software, if the user accidentally shuts down our push service, we can also prompt the user how to open allow to receive the push service (IOS8 later).

Attention:

    • When a push notification is issued, the push notification is not rendered if the current program is running in the foreground

    • When you click the push notification, the app that sent the push notification is automatically opened by default

    • Push notifications can be sent as scheduled regardless of whether the app is turned on or off

What is the difference between a message push and the usual fetch of data from the server?

    • When we get the data from the server, we will 主动向服务器 send a message, and then the server will send us the information we need, and the message push is when we are not in the chat state, even if the QQ software is not open, the server 主动向我们 sends a message, tell us some information.

Of course, message pushes and notifications (nsnotification) are different, although their use of the class name looks a bit similar.

    • Nsnotification is abstract, invisible.
    • Message push is visible (visible to the naked eye)
Local push

In iOS, push is divided into local push and remote push, local push does not require network (no server support required), common scenarios such as:

    • Event Alert class software, to our custom time, will pop up some information to tell us what to do.

    • Bookkeeping software, will remind us of some expenses and so on.

Let's learn a little bit about local push

Related classes Used (important)
    • To create a local push notification object
UILocalNotification *ln = [[UILocalNotification alloc] init];
    • Set local push notification properties
The trigger time of the push notification (when a push notification is sent) @property (nonatomic,copy) nsdate *firedate;//push notification details @property (nonatomic,copy) NSString * alertbody;//the action title (full title: "Swipe to" + alertaction) @property (nonatomic,copy) nsstring *alertaction;//sound file name @property on lock screen ( nonatomic,copy) nsstring *soundname;//app icon Digital @property (nonatomic) Nsinteger applicationiconbadgenumber;// How often do you send a push notification @property (nonatomic) nscalendarunit repeatinterval;//Click the push notification to open the app when the boot Picture @property (nonatomic,copy) NSString *alertlaunchimage;//Additional Information @property (nonatomic,copy) nsdictionary *userinfo;//time zone @property (nonatomic,copy ) Nstimezone *timezone; (generally set to [Nstimezone Defaulttimezone], follow the phone's time zone)//dispatch local push notifications (after the dispatch is complete, push notifications will be sent in a special time firedate) [[ UIApplication Sharedapplication] schedulelocalnotification:ln];//get all local push notifications scheduled (custom) @property (nonatomic,copy) Nsarray *scheduledlocalnotifications; (a push notification that has been issued and expired is automatically removed from this array even if the schedule ends)//Cancel dispatching local push notification-(void) cancellocalnotification :(uilocalnotification *) notification;-(void) cancelalllocalnotifications;//immediate local push notification-(void) PresentlocalnotificationnOW: (uilocalnotification *) notification; 
    • Call method when a user clicks a push message into the app
//当用户点击本地推送通知,会自动打开app,这里有2种情况//app并没有关闭,一直隐藏在后台//让app进入前台,并会调用AppDelegate的下面方法(并非重新启动app)- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;//app已经被关闭(进程已死)//启动app,启动完毕会调用AppDelegate的下面方法- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;//launchOptions参数通过UIApplicationLaunchOptionsLocalNotificationKey取出本地推送通知对象//当点击通知进入app时,launchOptions参数才会有值,当正常启动app时,launchOptions为null

Attention:

In iOS 8.0, if you want to use local notifications, you need permission from the user
Add the following code to the Didfinishlaunchingwithoptions method:

UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];[application registerUserNotificationSettings:settings];

Instance:

//在需要的地方注册本地消息推送    // 1.创建本地通知    UILocalNotification *localNote = [[UILocalNotification alloc] init];    // 2.设置本地通知的信息    // 2.1.设置提示信息    localNote.alertBody = @"吃饭了吗?";    // 2.2.设置通知弹出的时间    localNote.fireDate = [NSDate dateWithTimeIntervalSinceNow:5.0];    // 2.3.设置滑块显示的文字    localNote.alertAction = @"快点";    // 2.4.是否让上面的文字生效    localNote.hasAction = NO;    // 2.5.设置通知中心的标题    localNote.alertTitle = @"你大哥";    // 2.6.设置通知的声音    localNote.soundName = @"buyao.wav";    // 2.7.设置应用程序图标右上角的数字    localNote.applicationIconBadgeNumber = 10;    // 3.调度通知    //调度前要先把原来的通知取消    UIApplication *app = [UIApplication sharedApplication];    [app cancelAllLocalNotifications];    [app scheduleLocalNotification:localNote];

Implement the corresponding Jump method in the Appdelegate class

#import "AppDelegate.h" #define IS_IOS8 ([[[Uidevice currentdevice].systemversion Floatvalue] >= 8.0) @interface Appdelegate () @end @implementation appdelegate-(BOOL) Application: (UIApplication *) application     Didfinishlaunchingwithoptions: (nsdictionary *) launchoptions {/* Uiusernotificationtypenone = 0, no notification Uiusernotificationtypebadge = 1 << 0, change the top right corner of the application icon Uiusernotificationtypesound = 1 << 1, play the audio UI    Usernotificationtypealert = 1 << 2, whether to run the display banner */[application setapplicationiconbadgenumber:0]; if (Is_ios8) {uiusernotificationsettings *settings = [Uiusernotificationsettings Settingsfortypes:uiusernotificati Ontypebadge | Uiusernotificationtypealert |        Uiusernotificationtypesound Categories:nil];    [Application registerusernotificationsettings:settings]; }//If the application is started normally, then the launchoptions parameter is NULL//If the application is started by other means, then Launchoptions has a value, which stores the contents of the notification if (Launchoptions[uiapp LicationlaunchoptionslocalnotificatiOnKey]) {//Jump code executed when a local notification is received by the killed state [self jumptosession]; } return YES; When the program is not closed, click on the notification to enter the app will be called, if the program completely quit, click the notification to enter the app will only call the method above, do not call this method-(void) Application: (UIApplication *) application    Didreceivelocalnotification: (uilocalnotification *) notification{//write the Jump code here//If the application is in the foreground, you will still receive the notification, but you should not jump after receiving the notification    if (application.applicationstate = = uiapplicationstateactive) return; if (application.applicationstate = = uiapplicationstateinactive) {//Jump code executed when the app receives local notifications in the background [self Jumptosessio    n];    }}-(void) jumptosession{UILabel *redview = [[UILabel alloc] init];    Redview.backgroundcolor = [Uicolor Redcolor];    Redview.frame = CGRectMake (0, 100, 300, 400);    Redview.numberoflines = 0;    Redview.text = [NSString stringwithformat:@ "%@", launchoptions]; [Self.window.rootViewController.view Addsubview:redview];} @end
Remote push

Let's introduce the principle of remote push in iOS:

Let's make it clear that all the remote push messages received by all iOS devices are sent via Apple's server. Our own company's servers or third-party push servers are the push messages that will be sent to us first to Apple's servers, and then sent to us by Apple's servers.

Such as:

Therefore, our Apple device in the case of networking, will default and Apple's server to maintain a long connection (here does not explain the concept of long connection, you can understand that there is a line has been linked between the two, in order to keep the server constantly open and our device contact, Our device defaults to sending a heartbeat packet (a very small file) to the server every once in a while to tell the Apple server not to disconnect from our device.

Schematic explanation

Here's a detailed explanation of the remote push principle in iOS

The steps in 1-8 can explain the remote push process very well, and the client needs to do only a few steps:

    • 1: Send Device Udid and
      Bundle Identifier for Application
      to the APNS server

    • 2: Encrypted by Apple to generate a
      Devicetoken

    • 3: Send the current user's Devicetoken
      And the user's logo (such as ID or QQ) to their own company's server or third-party push server

    • 4: Tap event to listen for notifications

The remaining steps are implemented by the server side:

    • 4: Your own server or a third-party push server keeps the user information sent by the client on its own server

    • 5: When someone sends a message, from the server (according to Devicetoken) query to whom to send

    • 6: Send information to Apple server after query to send to someone

    • 7: Apple server based on the obtained Devicetoken and information, find the device and app to receive information, send the information to the user.

To debug the remote push feature of iOS, prerequisites:

1. Real Machine

2. Debug the required certificate file for push
1> Aps_development.cer: A computer can debug an app's push service
2> iphone5_qq.mobileprovision: A computer can use a device to debug a program

Three. Publish the app with push service, required certificate file
1> Aps_production.cer: If you publish a program that contains a push service, you must install this certificate
2> qq.mobileprovision: A computer can publish a program

Actual operation

Let's start with a real-life remote push feature.

Certificate configuration 01– Create app ID

Configuration-specific app ID

The approximate steps are as follows:

Select an explicit app ID first

Configuring a remote Push Debug certificate


Configure publishing certificates for remote pushes (configured using the second method)

Create a new project and change the bundle ID to the same name as configured above.

If it's still not working, check this out.

Install the configured certificate after it is downloaded.

The next step is to start processing the remote push message:

    • 1. Register our device with Apple and get to Devicetoken

Attention:
The registration method is different in iOS7 and iOS8

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    // 请求获取DeviceToken    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {        // 1.获取发送通知的权限        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];        [application registerUserNotificationSettings:settings];        // 2.注册远程通知        [application registerForRemoteNotifications];    } else {        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];    }    return YES;}//获取到deviceToken- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{    NSLog(@"%@", deviceToken);}
    • 2. Handling messages for remote notifications

Here are two ways to notice the difference between the two, more need to call

//这个方法可以处理当用户点击消息进入前台做一些操作- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{    NSLog(@"%@", userInfo);}
//这个方法可以实现在用户手机收到消息就可以在后台进行一些操作,例如更新UI//不过,这个方法要先设置后台模式,方法如下:/* 1.开启后台模式 2.调用completionHandler,告诉系统你现在是否有新的数据更新 3.userInfo添加一个字段:"content-available" : "1" : 只要添加了该字段,接受到通知都会在后台运行 */- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{    UIView *redView = [[UIView alloc] init];    redView.frame = CGRectMake(100, 100, 100, 100);    redView.backgroundColor = [UIColor redColor];    [self.window.rootViewController.view addSubview:redView];    completionHandler(UIBackgroundFetchResultFailed);}

To add a background mode method:

Introduction to test Tools

The following describes a tool for testing remote notifications Pushmebaby

    • Pushmebaby is an open-source Mac project for testing ANPs
    • It acts as a server and is very simple to use
    • It is responsible for submitting the content to Apple's APNs server, and Apple's APNs server then pushes the content to the user's device

    • Pushmebaby's homepage
      Https://github.com/stefanhafeneger/PushMeBaby

Steps to use:

    • Comment out not the error

    • Fill in the necessary information

      • Devicetoken: A token used to locate a device

      • Payload: Push Content

    • Change the push debug certificate to the name Apns.cer, and add it to the Pushmebaby project

    • Command + R to start the program, then click Push
      Next, you can receive remote push notifications on your device

Popular third-party push (Aurora push)

What is Jpush

A set of remote push solutions that support Android and iOS two platforms
It quickly adds push capabilities to iOS apps, reducing the amount of effort and complexity required to integrate APNs

For more information, refer to Jpush official website: https://www.jpush.cn

The steps for integrating the iOS SDK can be consulted
http://docs.jpush.cn/pages/viewpage.action?pageId=2621727

ios-local push and remote push, commonly used three-way push and common test methods, push the implementation and the principle of explanation (reprinted from Xue Silver [email protected])

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.