IOS-推送通知

一、推送通知

注意:这里说的推送通知跟NSNotification有所区别
NSNotification是抽象的,不可见的
推送通知是可见的(能用肉眼看到)
 
iOS中提供了2种推送通知
本地推送通知(Local Notification)
远程推送通知(Remote Notification)
 
二、本地推送通知
1.什么是本地推送通知
顾名思义,就是不需要联网就能发出的推送通知(不需要服务器的支持)
 
2.本地推送通知的使用场景
常用来定时提醒用户完成一些任务,比如
清理垃圾、记账、买衣服、看电影、玩游戏
 
3.如何发出本地推送通知
创建本地推送通知对象

UILocalNotification *ln = [[UILocalNotification alloc] init];

设置本地推送通知属性
推送通知的触发时间(何时发出推送通知)

@property(nonatomic,copy) NSDate *fireDate;

推送通知的具体内容

@property(nonatomic,copy) NSString *alertBody;

在锁屏时显示的动作标题(完整标题:“滑动来” + alertAction)

@property(nonatomic,copy) NSString *alertAction;

音效文件名

@property(nonatomic,copy) NSString *soundName;

app图标数字

@property(nonatomic) NSInteger applicationIconBadgeNumber;

调度本地推送通知(调度完毕后,推送通知会在特地时间fireDate发出)

[[UIApplication sharedApplication] scheduleLocalNotification:ln];

获得被调度(定制)的所有本地推送通知

@property(nonatomic,copy) NSArray *scheduledLocalNotifications;

(已经发出且过期的推送通知就算调度结束,会自动从这个数组中移除)

取消调度本地推送通知

- (void)cancelLocalNotification:(UILocalNotification *)notification;

- (void)cancelAllLocalNotifications;

立即发出本地推送通知

- (void)presentLocalNotificationNow:(UILocalNotification *)notification;

每隔多久重复发一次推送通知

@property(nonatomic) NSCalendarUnit repeatInterval;

点击推送通知打开app时显示的启动图片

@property(nonatomic,copy) NSString *alertLaunchImage;

附加的额外信息

@property(nonatomic,copy) NSDictionary *userInfo;

时区

@property(nonatomic,copy) NSTimeZone *timeZone;

(一般设置为[NSTimeZone defaultTimeZone] ,跟随手机的时区)

4.点击本地推送通知

当用户点击本地推送通知,会自动打开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取出本地推送通知对象
 
 

三、远程推送通知

1.什么是远程推送通知
顾名思义,就是从远程服务器推送给客户端的通知(需要联网)
远程推送服务,又称为APNs(Apple Push Notification Services)
2.为什么需要远程推送通知?
传统获取数据的局限性
只要用户关闭了app,就无法跟app的服务器沟通,无法从服务器上获得最新的数据内容
3.远程推送通知可以解决以上问题
不管用户打开还是关闭app,只要联网了,都能接收到服务器推送的远程通知
 
4.远程推送通知使用须知
所有的苹果设备,在联网状态下,都会与苹果的服务器建立长连接
什么是长连接
只要联网了,就一直建立连接
长连接的作用
时间校准
系统升级
查找我的iPhone
.. ...
长连接的好处
数据传输速度快
数据保持最新状态
 
5.属性
客户端如果想接收APNs的远程推送通知,必须先注册(得到用户的授权)
一般在App启动完毕后就马上注册

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    // 注册远程通知

       UIRemoteNotificationType type = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound;

    [application registerForRemoteNotificationTypes:type];

    return YES;

如果是第一次注册,会弹出右边的对话框
 
注册成功后会调用AppDelegate的下面方法,得到设备的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取出服务器返回的字典内容
 
 
6.从获得deviceToken 到 推送消息给设备 的过程
 

一.开发iOS程序的推送功能, iOS端需要做的事

1.请求苹果获得deviceToken

2.得到苹果返回的deviceToken

3.发送deviceToken给公司的服务器

4.监听用户对通知的点击

二.调试iOS的远程推送功能, 必备条件:

1.真机

2.调试推送需要的证书文件

1> aps_development.cer : 某台电脑就能调试某个app的推送服务

2> ios_development.cer : 让电脑具备真机调试的能力(调试设备)

3> iphone5_qq.mobileprovision : 某台电脑就能利用某台设备调试某个程序

三.发布具有推送服务的app

1> aps_production.cer : 如果发布的程序中包含了推送服务,就必须安装这个证书

2> ios_distribution.cer  : 让电脑具备发布程序的能力

3> qq.mobileprovision  : 某台电脑就能发布某个程序

远程推送

  1 //
  2 //  AppDelegate.m
  3 //  01-获取DeviceToken
  4 //
  5 //  Created by apple on 14/11/10.
  6 //  Copyright (c) 2014年 heima. All rights reserved.
  7 //
  8 
  9 #import "AppDelegate.h"
 10 
 11 @interface AppDelegate ()
 12 
 13 @end
 14 
 15 @implementation AppDelegate
 16 
 17 
 18 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 19     // Override point for customization after application launch.
 20     
 21     if ([UIDevice currentDevice].systemVersion.doubleValue <= 8.0) {
 22         // 不是iOS8
 23         UIRemoteNotificationType type = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert;
 24         // 当用户第一次启动程序时就获取deviceToke
 25         // 该方法在iOS8以及过期了
 26         // 只要调用该方法, 系统就会自动发送UDID和当前程序的Bunle ID到苹果的APNs服务器
 27         [application registerForRemoteNotificationTypes:type];
 28     }else
 29     {
 30         // iOS8
 31         UIUserNotificationType type = UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
 32         
 33         UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
 34         // 注册通知类型
 35         [application registerUserNotificationSettings:settings];
 36         
 37         // 申请试用通知
 38         [application registerForRemoteNotifications];
 39     }
 40     
 41     // 1.取出数据
 42     NSDictionary *userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
 43     
 44     if (userInfo) {
 45         static int count = 0;
 46         count++;
 47         UILabel *label = [[UILabel alloc] init];
 48         label.frame = CGRectMake(0, 40, 200, 200);
 49         label.numberOfLines = 0;
 50         label.textColor = [UIColor whiteColor];
 51         label.font = [UIFont systemFontOfSize:11];
 52         label.backgroundColor = [UIColor orangeColor];
 53         label.text = [NSString stringWithFormat:@" %@ 
 %d", userInfo, count];
 54         [self.window.rootViewController.view addSubview:label];
 55     }
 56     
 57 
 58     return YES;
 59 }
 60 
 61 /**
 62  *  获取到用户对应当前应用程序的deviceToken时就会调用
 63  */
 64 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
 65 {
 66     NSLog(@"%@", deviceToken);
 67     // <47e58207 31340f18 ed83ba54 f999641a 3d68bc7b f3e2db29 953188ec 7d0cecfb>
 68     // <286c3bde 0bd3b122 68be655f 25ed2702 38e31cec 9d54da9f 1c62325a 93be801e>
 69 }
 70 
 71 /*
 72  ios7以前苹果支持多任务, iOS7以前的多任务是假的多任务
 73  而iOS7开始苹果才真正的推出了多任务
 74  */
 75 // 接收到远程服务器推送过来的内容就会调用
 76 // 注意: 只有应用程序是打开状态(前台/后台), 才会调用该方法
 77 /// 如果应用程序是关闭状态会调用didFinishLaunchingWithOptions
 78 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
 79 {
 80     /*
 81      如果应用程序在后台 , 只有用户点击了通知之后才会调用
 82      如果应用程序在前台, 会直接调用该方法
 83      即便应用程序关闭也可以接收到远程通知
 84      */
 85     NSLog(@"%@", userInfo);
 86     
 87 //    static int count = 0;
 88 //    count++;
 89 //    UILabel *label = [[UILabel alloc] init];
 90 //    label.frame = CGRectMake(0, 250, 200, 200);
 91 //    label.numberOfLines = 0;
 92 //    label.textColor = [UIColor whiteColor];
 93 //    label.text = [NSString stringWithFormat:@"%@ 
 %d", userInfo, count];
 94 //    label.font = [UIFont systemFontOfSize:11];
 95 //    label.backgroundColor = [UIColor grayColor];
 96 //    [self.window.rootViewController.view addSubview:label];
 97 }
 98 
 99 //接收到远程服务器推送过来的内容就会调用
100 // ios7以后用这个处理后台任务接收到得远程通知
101 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
102 {
103     /*
104      UIBackgroundFetchResultNewData, 成功接收到数据
105      UIBackgroundFetchResultNoData, 没有;接收到数据
106      UIBackgroundFetchResultFailed 接收失败
107      
108      */
109 //    NSLog(@"%s",__func__);
110 //    NSLog(@"%@", userInfo);
111     
112     NSNumber *contentid =  userInfo[@"content-id"];
113     if (contentid) {
114         UILabel *label = [[UILabel alloc] init];
115         label.frame = CGRectMake(0, 250, 200, 200);
116         label.numberOfLines = 0;
117         label.textColor = [UIColor whiteColor];
118         label.text = [NSString stringWithFormat:@"%@", contentid];
119         label.font = [UIFont systemFontOfSize:30];
120         label.backgroundColor = [UIColor grayColor];
121         [self.window.rootViewController.view addSubview:label];
122         //注意: 在此方法中一定要调用这个调用block, 告诉系统是否处理成功.
123         // 以便于系统在后台更新UI等操作
124         completionHandler(UIBackgroundFetchResultNewData);
125     }else
126     {
127         completionHandler(UIBackgroundFetchResultFailed);
128     }
129     
130 }
131 @end

本地推送

 1 //
 2 //  MJViewController.m
 3 //  06-本地通知
 4 //
 5 //  Created by apple on 14-6-4.
 6 //  Copyright (c) 2014年 itcast. All rights reserved.
 7 //
 8 
 9 #import "MJViewController.h"
10 
11 @interface MJViewController ()
12 - (IBAction)addLocalNote;
13 - (IBAction)cancelLocalNote;
14 
15 @end
16 
17 @implementation MJViewController
18 
19 - (void)viewDidLoad
20 {
21     [super viewDidLoad];
22     // Do any additional setup after loading the view, typically from a nib.
23 }
24 
25 - (IBAction)addLocalNote {
26     // 1.创建通知
27     UILocalNotification *localNote = [[UILocalNotification alloc] init];
28     
29     // 2.设置属性
30     localNote.alertAction = @"开始玩游戏"; // 操作标题
31     localNote.alertBody = @"都好几天了, 你赶紧用一下我吧!!!"; // 正文
32     localNote.applicationIconBadgeNumber = 5;
33 //    localNote.repeatInterval = NSCalendarUnitMinute;
34     localNote.alertLaunchImage = @"Default"; // 点击通知, 打开程序时候现实的启动图片
35     localNote.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
36     // 3.注册通知(添加)
37     UIApplication *app = [UIApplication sharedApplication];
38     [app cancelAllLocalNotifications];
39     [app scheduleLocalNotification:localNote];
40 }
41 
42 - (IBAction)cancelLocalNote {
43     UIApplication *app = [UIApplication sharedApplication];
44     [app cancelAllLocalNotifications];
45 }
46 @end
 1 //
 2 //  MJAppDelegate.m
 3 //  06-本地通知
 4 //
 5 //  Created by apple on 14-6-4.
 6 //  Copyright (c) 2014年 itcast. All rights reserved.
 7 //
 8 
 9 #import "MJAppDelegate.h"
10 
11 @interface MJAppDelegate()
12 //@property (nonatomic, weak) UILabel *label;
13 @end
14 
15 @implementation MJAppDelegate
16 
17 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
18 {
19     UILabel *label = [[UILabel alloc] init];
20     label.frame = CGRectMake(0, 30, 200, 70);
21     label.backgroundColor = [UIColor redColor];
22     label.text = [NSString stringWithFormat:@"%@", launchOptions];
23     [self.window.rootViewController.view addSubview:label];
24 //    self.label = label;
25     
26     // Override point for customization after application launch.
27     
28     NSLog(@"didFinishLaunchingWithOptions---");
29     return YES;
30 }
31 
32 /**
33  说明用户点击通知, 进入了程序(程序还在运行中, 程序并没有被关掉)
34  */
35 - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
36 {
37     UILabel *label = [[UILabel alloc] init];
38     label.frame = CGRectMake(0, 100, 200, 50);
39     label.backgroundColor = [UIColor blueColor];
40     label.text = @"didReceiveLocalNotification";
41     [self.window.rootViewController.view addSubview:label];
42     
43     NSLog(@"didReceiveLocalNotification");
44 }
45                             
46 - (void)applicationWillResignActive:(UIApplication *)application
47 {
48     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
49     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
50 }
51 
52 - (void)applicationDidEnterBackground:(UIApplication *)application
53 {
54     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
55     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
56 }
57 
58 - (void)applicationWillEnterForeground:(UIApplication *)application
59 {
60     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
61 }
62 
63 - (void)applicationDidBecomeActive:(UIApplication *)application
64 {
65     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
66 }
67 
68 - (void)applicationWillTerminate:(UIApplication *)application
69 {
70     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
71 }
72 
73 @end
原文地址:https://www.cnblogs.com/oc-bowen/p/5338413.html