iOS推送通知“黄金宝典”

1. App关闭时接收到他推送通知,经过点击推送通知来启动App

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

在程序启动完成后,在此方法中能够获得推送通知的类容,此处又分为远程通知和本地通知的区别。ios

远程通知app

NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

本地通知spa

UILocalNotification *localNoti = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
NSDictionary * userInfo = localNoti.userInfo;

这里,为了让主界面先加载完成,通常须要延迟一小段时间后再去处理推送通知,push出相应的响应页面等。code

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self didReceiveNotification:userInfo];
            });

2.App正在运行时接收到推送通知

远程通知get

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;

本地通知it

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;

App状态io

UIApplicationStateActive, // 激活状态,用户正在使用App
    UIApplicationStateInactive, // 不激活状态,用户切换到其余App、按Home键回到桌面、拉下通知中心
    UIApplicationStateBackground // 在后台运行

根据application.applicationState的状态,判断执行哪一种动做。class

 

三、检测客户端是否打开了接收通知的功能后台

检测客户端是否打开了通知:
if (IOS8) { //iOS8以上包含iOS8
        UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];

        if(UIUserNotificationTypeNone != setting.types) {
            NSLog(@"用户打开了通知");
        }else{
            [self showAlert];
        }
    }else{ // ios7 一下
        UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        if(UIRemoteNotificationTypeNone != type){
            NSLog(@"用户打开了通知");
        }else{
            [self showAlert];
        }
    }


//用户没打开接受通知功能给出提示
-(void)showAlert{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"“凤凰云健康”想给您发送推送通知" message:@"“通知”可能包括提醒、声音和图标标记。这些可在“设置”中配置。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"肯定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
相关文章
相关标签/搜索