2.后台运行及程序退出 会调用的方法
后台运行: 指的是程序已经打开, 用户看不见程序的界面, 如锁屏和按Home键.
程序退出: 指的是程序没有运行, 或者通过双击Home键,关闭了程序.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler
{
NSDictionary *userInfo = response.notification.request.content.userInfo;
//后台及退出推送 显示绿色Label
[self showLabelWithUserInfo:userInfo color:[UIColor greenColor]];
completionHandler();
}
3.静默推送通知 会调用的方法
静默推送: iOS7以后出现, 不会出现提醒及声音.
要求:
推送的payload中不能包含alert及sound字段
需要添加content-available字段, 并设置值为1
例如: {"aps":{"content-available":"1"},"PageKey”":"2"}
//如果是以前的旧框架, 此方法 前台/后台/退出/静默推送都可以处理
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
//静默推送 显示蓝色Label
[self showLabelWithUserInfo:userInfo color:[UIColor blueColor]];
completionHandler(UIBackgroundFetchResultNewData);
}
4.处理通知的公用方法
开发中, 点击通知的逻辑应当看自己程序的需求.
这里为了方便演示, 简单的将通知的值, 通过UILabel显示在主界面上.
- (void)showLabelWithUserInfo:(NSDictionary *)userInfo color:(UIColor *)color
{
UILabel *label = [UILabel new];
label.backgroundColor = color;
label.frame = CGRectMake(0, 250, [UIScreen mainScreen].bounds.size.width, 300);
label.text = userInfo.description;
label.numberOfLines = 0;
[[UIApplication sharedApplication].keyWindow addSubview:label];
}
三、测试远程推送
PushMeBaby是一个简单的模拟服务器的Mac小程序, 可以将内容提交给苹果的APNs服务器.
为了测试远程通知, 我们需要安装此程序.
请前往www.github.com, 搜索并下载PushMeBaby
使用时:
编译该项目, 如果报错, 则注释报错的代码, 不影响实际使用.
进入苹果开发者网站, 获取真机调试用的远程推送证书, 导入到项目中
将之前获取到的DeviceToken, 及测试的文字, 填入该项目中的AppDelegate中的init方法中.
运行此项目, 会出现一个Mac小程序, 点击Push即可发送远程通知.
- (id)init {
self = [super init];
if(self != nil) {
self.deviceToken = @"de20184c ef0461d5 12c76422 f5b78240 5f657e18 ebf91c9f 01d5560c e2913102";
self.payload = @"{"aps":{"alert":{"title":"himeao","subtitle":"自学成才","body":"iOS10远程&本地推送教程"},"badge":1,"sound":"default"},"PageKey":"1"}";
self.certificate = [[NSBundle mainBundle] pathForResource:@"aps_development" ofType:@"cer"];
}
return self;
}










