iOS development-ANPs push notifications

Source: Internet
Author: User

Push Notifications

Note: There's a difference between push notifications and nsnotification.
Nsnotification is abstract, invisible.
Push notifications are visible (can be seen with the naked eye)

2 push notifications available in iOS
Local push notifications (locally Notification)
Remote push notifications (remotes Notification)

Summary of the rendering effect of push notifications

To summarize, push notifications have 5 different rendering effects
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)

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

Local push Notifications

What is a local push notification
As the name implies, it is a push notification that does not need to be networked (no server support required)

Usage scenarios for local push notifications
Often used to regularly remind users to do some tasks, such as
Cleaning up trash, bookkeeping, buying clothes, watching movies, playing games

How to issue a local push notification
//Create a local push notification objectuilocalnotification*LN = [[uilocalnotificationALLOC] init];//Set local push notification propertiestrigger time for push notifications (when push notifications are sent)@property(nonatomic, copy)NSDate*firedate;specific content of the push notification@property(nonatomic, copy)NSString*alertbody;//Action caption displayed on lock screen (full title: "Swipe to" + alertaction)@property(nonatomic, copy)NSString*alertaction;//audio file name@property(nonatomic, copy)NSString*soundname;//app icon Number@property(nonatomic)NsintegerApplicationiconbadgenumber;
//调度本地推送通知(调度完毕后,推送通知会在特地时间fireDate发出)[[UIApplication sharedApplication] scheduleLocalNotification:ln];//获得被调度(定制)的所有本地推送通知@property(nonatomicNSArray *scheduledLocalNotifications;(已经发出且过期的推送通知就算调度结束,会自动从这个数组中移除)//取消调度本地推送通知- (void)cancelLocalNotification:(UILocalNotification *)notification;- (void)cancelAllLocalNotifications;//立即发出本地推送通知- (void)presentLocalNotificationNow:(UILocalNotification *)notification;
Additional properties for local push notifications
//每隔多久重复发一次推送通知@property(nonatomic) NSCalendarUnit repeatInterval;//点击推送通知打开app时显示的启动图片@property(nonatomicNSString *alertLaunchImage;//附加的额外信息@property(nonatomicNSDictionary *userInfo;//时区@property(nonatomic,copy) NSTimeZone *timeZone;(一般设置为[NSTimeZone defaultTimeZone] ,跟随手机的时区)
Click Local push Notifications
//当用户点击本地推送通知,会自动打开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取出本地推送通知对象
Remote push Notifications

What is remote push notification
As the name implies, the notification that is pushed from the remote server to the client (requires networking)
Remote Push service, also known as APNs (Apple push Notification services)

Why do I need remote push notifications?
Limitations of traditional data acquisition
As long as the user closes the app, they can't communicate with the app's server and get the latest data content from the server.

Remote push notifications can solve these problems
No matter whether the user opens or closes the app, you can receive remote notification of the server push as long as the internet is connected

Tips for using remote push notifications

All Apple devices, in a networked state, will have long connections with Apple's servers
What is a long connection
As long as the network is connected, it has been established.

Effects of long connections
Time Calibration
System upgrade
Find My iphone
.. ...

Benefits of long connections
Fast data transfer speed
Keep your data up to date

I. Developing the push feature of iOS programs, what iOS needs to do
1. Request Apple to get Devicetoken
2. Get Apple back to Devicetoken
3. Send Devicetoken to the company's servers
4. Listen for user clicks on notifications

Two. Debugging 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> Ios_development.cer: The ability to debug a computer with a real machine (commissioning device)
3> iphone5_qq.mobileprovision: A computer can use a device to debug a program

Three. Publish Apps with push service
1> Aps_production.cer: If you publish a program that contains a push service, you must install this certificate
2> Ios_distribution.cer: The ability to release programs to your computer
3> qq.mobileprovision: A computer can publish a program

Registering Remote Notifications
//客户端如果想接收APNs的远程推送通知,必须先注册(得到用户的授权)//一般在App启动完毕后就马上注册- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    // 注册远程通知       type = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound;    [application registerForRemoteNotificationTypes:type];    return YES;}
//will call appdelegate  after successful registration The following method, get the device Devicetoken  - ( void)  Application: (uiapplication  *)  Application Didregisterforremotenotificationswithdevicetoken: ( NSData  *)  devicetoken{nslog (@ "%@" , Devicetoken ) ;}   
//当用户点击远程推送通知,会自动打开app,这里有2种情况//app并没有关闭,一直隐藏在后台//让app进入前台,并会调用AppDelegate的下面方法(并非重新启动app)- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;//app已经被关闭(进程已死)//启动app,启动完毕会调用AppDelegate的下面方法- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;launchOptions参数通过UIApplicationLaunchOptionsRemoteNotificationKey取出服务器返回的字典内容
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

Remote Push Get Devicetoken instance
 @interface appdelegate ()@end @implementation appdelegate - (BOOL) Application: (uiapplication*) Application Didfinishlaunchingwithoptions: (nsdictionary*) Launchoptions {//Override point for customization after application launch.    if([Uidevice Currentdevice]. Systemversion. Doublevalue<=8.0) {//Not iOS8Uiremotenotificationtype type = Uiremotenotificationtypebadge | Uiremotenotificationtypesound | Uiremotenotificationtypealert;//Get devicetoke When the user starts the program for the first time        //This method is iOS8 and outdated.        //As long as this method is called, the system will automatically send the Bunle ID of Udid and the current program to Apple's APNs server[Application Registerforremotenotificationtypes:type]; }Else{//IOS8Uiusernotificationtype type = Uiusernotificationtypebadge | Uiusernotificationtypealert |        Uiusernotificationtypesound; Uiusernotificationsettings *settings = [uiusernotificationsettings settingsfortypes:type categories:Nil];//Registration notification type[Application registerusernotificationsettings:settings];//Request a trial notice[Application registerforremotenotifications]; }//1. Remove Data    nsdictionary*userinfo = Launchoptions[uiapplicationlaunchoptionsremotenotificationkey];if(UserInfo) {Static intCount =0; count++;UILabel*label = [[UILabelALLOC] init]; Label. Frame= CGRectMake (0, +, $, $); Label. NumberOfLines=0; Label. TextColor= [UicolorWhitecolor]; Label. Font= [UifontSystemfontofsize: One]; Label. BackgroundColor= [UicolorOrangecolor]; Label. Text= [NSStringstringwithformat:@"%@ \ n%d", UserInfo, Count]; [ Self. Window. Rootviewcontroller. ViewAddsubview:label]; }return YES;}/** * Gets called when the user corresponds to the devicetoken of the current application */- (void) Application: (uiapplication*) Application Didregisterforremotenotificationswithdevicetoken: (NSData *) devicetoken{NSLog(@"%@", Devicetoken);//<47e58207 31340f18 ed83ba54 f999641a 3d68bc7b f3e2db29 953188ec 7d0cecfb>    //<286c3bde 0bd3b122 68be655f 25ed2702 38e31cec 9d54da9f 1c62325a 93be801e>}/ * iOS7 previous Apple support multitasking, iOS7 previous multitasking is fake multitasking and iOS7 started Apple to really launch multitasking * ///received by the remote server pushed over the content will be called//Note: This method is only called if the application is open (foreground/background)/// If the application is off the status will call Didfinishlaunchingwithoptions- (void) Application: (uiapplication*) Application Didreceiveremotenotification: (nsdictionary*) userinfo{/ * If the application is in the background, it will be called only if the user clicks on the notification. If the application is in the foreground, the method will be called directly even if the application shuts down or receives a remote notification * /    NSLog(@"%@", UserInfo);//static int count = 0;//count++;//UILabel *label = [[UILabel alloc] init];//Label.frame = CGRectMake (0, +,--);//label.numberoflines = 0;//Label.textcolor = [Uicolor whitecolor];//Label.text = [nsstring stringwithformat:@ "%@ \ n%d", UserInfo, Count];//Label.font = [Uifont systemfontofsize:11];//Label.backgroundcolor = [Uicolor graycolor];//[Self.window.rootViewController.view Addsubview:label];}//received by the remote server pushed over the content will be called//IOS7 receive remote notifications with this processing background task later- (void) Application: (uiapplication*) Application Didreceiveremotenotification: (nsdictionary*) UserInfo Fetchcompletionhandler: (void(^) (Uibackgroundfetchresult)) completionhandler{/ * Uibackgroundfetchresultnewdata, successfully received data uibackgroundfetchresultnodata, no; received data Uibackgroundfetchresult Failed Receive failed * ///NSLog (@ "%s", __func__);//NSLog (@ "%@", userInfo);    NSNumber*contentid = userinfo[@"Content-id"];if(ContentID) {UILabel*label = [[UILabelALLOC] init]; Label. Frame= CGRectMake (0, -, $, $); Label. NumberOfLines=0; Label. TextColor= [UicolorWhitecolor]; Label. Text= [NSStringstringwithformat:@"%@", ContentID]; Label. Font= [UifontSystemfontofsize: -]; Label. BackgroundColor= [UicolorGraycolor]; [ Self. Window. Rootviewcontroller. ViewAddsubview:label];//Note: Be sure to call this call block in this method to tell the system whether the process is successful.        //To enable the system to update the UI in the background and other operationsCompletionhandler (Uibackgroundfetchresultnewdata); }Else{Completionhandler (uibackgroundfetchresultfailed); }}@end

iOS development-ANPs push notifications

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.