一:下面是本人在工作中的一点随记,方便以后查用,其中需要您的App打开了background mode里的Remote Notifications项,且需要APNS的payload里指定content-available键为1时
1.AppDelegate+XPush.h
#import "AppDelegate.h"
@interface AppDelegate (XPush)
@property (nonatomic, copy) NSString *token;
@property (nonatomic, assign) NSInteger badgeNumber;
@end
2.AppDelegate+XPush.m
#import "AppDelegate+XPush.h"
#import <objc/runtime.h>
#import "HttpHelper.h"
#ifndef __OPTIMIZE__
#define NSLog(...) NSLog(__VA_ARGS__)
#else
#define NSLog(...) {}
#endif
@implementation AppDelegate (XPush)
static char tokenKey;
NSInteger _badgeNumber;
- (NSString *)token
{
return objc_getAssociatedObject(self, &tokenKey);
}
- (void)setToken:(NSString *)token
{
objc_setAssociatedObject(self, &tokenKey, token, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSInteger)badgeNumber
{
NSLog(@"get---%ld",_badgeNumber);
return _badgeNumber;
}
- (void)setBadgeNumber:(NSInteger)badgeNumber
{
NSLog(@"set---%ld",badgeNumber);
_badgeNumber = badgeNumber;
}
//当app在后台运行时,激活APP时会走这个方法,在这里面里可以对推送消息做响应的处理
-(void)applicationDidBecomeActive:(UIApplication *)application{
// //把icon上的标记数字设置为0,
// application.applicationIconBadgeNumber = 0;
// [[UIApplication sharedApplication] cancelAllLocalNotifications];
// NSLog(@"----self.badgeNumber----%ld",self.badgeNumber);
// self.badgeNumber = 0;
// NSLog(@"----把icon上的标记数字设置为0----");
}
- (id)init
{
/** If you need to do any extra app-specific initialization, you can do it here
* -jm
**/
NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
[cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
int cacheSizeMemory = 8 * 1024 * 1024; // 8MB
int cacheSizeDisk = 32 * 1024 * 1024; // 32MB
#if __has_feature(objc_arc)
NSURLCache* sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
#else
NSURLCache* sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"] autorelease];
#endif
[NSURLCache setSharedURLCache:sharedCache];
self = [super init];
//注册消息推送
#ifdef __IPHONE_8_0
//Right, that is the point
/*UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];*/
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
#else
//register to receive notifications
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
#endif
return self;
}
#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
//register to receive notifications注册接收通知
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler
{
//handle the actions
if ([identifier isEqualToString:@"declineAction"]){
}
else if ([identifier isEqualToString:@"answerAction"]){
}
}
#endif
//获取DeviceToken成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
// NSLog(@"deviceToken-%@",token);
self.token = token;
NSDictionary *dictionarry = [[NSDictionary alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"PushConfig" ofType:@"plist"]];
NSString *appkey = [dictionarry objectForKey:@"APP_KEY"];
//1.请求url
NSString *url = @"http://192.168.1/push";
//2.拼接请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"appkey"] = appkey;
params[@"token"] = token;
NSLog(@"params:%@",params);
//3.有网络才发送请求
if([HttpHelper NetWorkIsOK]){
//发送请求,并且得到返回的数据
[HttpHelper post:url RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//传回数据回调
NSLog(@"token发送成功");
}];
}
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(@"error-%@",error);
}
//处理收到的消息推送
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
NSLog(@"userInfo------------------:%@",userInfo);
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
NSLog(@"userInfo---------^^^^^---------:%@",userInfo);
//远程消息发送过来的时候,app正在运行
if (application.applicationState == UIApplicationStateActive) {
// 转换成一个本地通知,显示到通知栏
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// 通知参数
localNotification.userInfo = userInfo;
// 通知被触发时播放的声音
localNotification.soundName = UILocalNotificationDefaultSoundName;
// 通知内容
localNotification.alertBody = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
// 设置触发通知的时间
localNotification.fireDate = [NSDate date];
// 执行通知注册
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}else{
if (self.badgeNumber) {
self.badgeNumber++;
}else{
//self.badgeNumber = application.applicationIconBadgeNumber;
self.badgeNumber = 1;
}
application.applicationIconBadgeNumber = self.badgeNumber;
}
}
//应用每次被切换到前台的时候
-(void)applicationWillEnterForeground:(UIApplication *)application{
NSLog(@"-----------WillEnterForeground----------");
//把icon上的标记数字设置为0
application.applicationIconBadgeNumber = 0;
self.badgeNumber = 0;
}
//进入后台后
-(void)applicationDidEnterBackground:(UIApplication *)application{
NSLog(@"--------DidEnterBackground--------------");
//把icon上的标记数字设置为0
NSLog(@"----application.applicationIconBadgeNumber----%ld",application.applicationIconBadgeNumber);
application.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSLog(@"----self.badgeNumber----%ld",self.badgeNumber);
self.badgeNumber = 0;
NSLog(@"----把icon上的标记数字角标清零,取消所有本地通知----");
}
@end
2.ios10推送更新,推荐几个博客
http://www.jianshu.com/p/2f3202b5e758
http://www.open-open.com/lib/view/open1473734681248.html
http://blog.csdn.net/qq_25527655/article/details/52597349
http://blog.csdn.net/u012847940/article/details/51801078
http://www.jianshu.com/p/f5337e8f336d这篇文章很好
3.借用网友博客里面的一段内容
UserNotifications(用户通知)
iOS 10 中将通知相关的 API 都统一了,在此基础上很多用户定义的通知,并且可以捕捉到各个通知状态的回调.以前通知的概念是:大家想接受的提前做好准备,然后一下全两分发,没收到也不管了,也不关心发送者,现在的用户通知做成了类似于网络请求,先发一个request得到response的流程,还封装了error,可以在各个状态的方法中做一些额外的操作,并且能获得一些字段,比如发送者之类的.这个功能的头文件是:#import
主要有以下文件:
#import <UserNotifications/NSString+UserNotifications.h>
#import <UserNotifications/UNError.h>
#import <UserNotifications/UNNotification.h>
#import <UserNotifications/UNNotificationAction.h>
#import <UserNotifications/UNNotificationAttachment.h>
#import <UserNotifications/UNNotificationCategory.h>
#import <UserNotifications/UNNotificationContent.h>
#import <UserNotifications/UNNotificationRequest.h>
#import <UserNotifications/UNNotificationResponse.h>
#import <UserNotifications/UNNotificationSettings.h>
#import <UserNotifications/UNNotificationSound.h>
#import <UserNotifications/UNNotificationTrigger.h>
#import <UserNotifications/UNUserNotificationCenter.h>
#import <UserNotifications/UNNotificationServiceExtension.h>