iOS开发总结iOS开发iOS Developer

iOS10推送适配完整说明

2016-10-09  本文已影响331人  Auditore

一年一度的iOS大版本更新又开始了,对于不明真相吃瓜群众来说真是太好啦!对于我们程序员却意味着disaster...这次的推送架构完全推翻以往,所以得从新适配,话不多说,开始吧。
1.在targets的Capabiliies内Push Notifications选项开关打开


Paste_Image.png

然后Background Modes打开如下几个选项

Paste_Image.png

友情提示上图几个选项,如果你应用内没有需要在后台音频播放或者位置更新,第一和第二项还是别勾上了,免得被App Store审核bb...我的刚提交两天就给我干下来返工了,555

General内导入UserNotifications.framework

Paste_Image.png

2.进入Appdelegate.m文件

2.1)

#import <UserNotifications/UserNotifications.h>

遵循UNUserNotificationCenterDelegate协议

@interface AppDelegate()<UNUserNotificationCenterDelegate>

2.2)

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

方法内调用registRemoteNotifications方法

//20160930 注册通知APNS

[self registRemoteNotifications];

该方法具体如下

1.- (void)registRemoteNotifications {

if ([[[UIDevice currentDevice] systemVersion]floatValue]>=10.0) {
    //申请用户同意
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"succeeded!");
        }
        if (granted) {
            
            [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                
                NSLog(@"remoteNotificationSetting: %@", settings);
                
            }];
        }
    }];
    
}
float ios_version = [[[UIDevice currentDevice] systemVersion] floatValue];

if (ios_version >= 8.0){//iOS8-iOS10
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}
else {
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert];
}

}

2.3)
再实现如下两个代理方法

#pragma mark --ios10推送回调

//前台回调

1)- (void)userNotificationCenter:(UNUserNotificationCenter*)center willPresentNotification:(UNNotification
*)notification withCompletionHandler:(void(^)(UNNotificationPresentationOptions))completionHandler

{

[self application:[UIApplication sharedApplication] didReceiveRemoteNotification:notification.request.content.userInfo];

}

//后台回调

2) - (void)userNotificationCenter:(UNUserNotificationCenter*)center didReceiveNotificationResponse:(UNNotificationResponse
*)response withCompletionHandler:(void(^)())completionHandler

{

[self application:[UIApplication sharedApplication] didReceiveRemoteNotification:response.notification.request.content.userInfo];

}

完成

上一篇 下一篇

猜你喜欢

热点阅读