iOS本地推送的实现,兼容iOS8

AppDelegate.m中的代码

// AppDelegate.m中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 处理iOS8本地推送不能收到的问题
    float sysVersion=[[UIDevice currentDevice]systemVersion].floatValue;
    if (sysVersion>=8.0) {
        UIUserNotificationType type=UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
        UIUserNotificationSettings *setting=[UIUserNotificationSettings settingsForTypes:type categories:nil];
        [[UIApplication sharedApplication]registerUserNotificationSettings:setting];
    }
    return YES;
}

// 接收本地推送(AppDelegate.m中添加)
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"标题" message:notification.alertBody delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
    
    // 图标上的数字减1
    application.applicationIconBadgeNumber -= 1;
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // 直接打开app时,图标上的数字清零
    application.applicationIconBadgeNumber = 0;
}


在调用的类中添加的代码

// 进行推送的方法
// 设置本地推送参数,并进行推送
- (void)scheduleNotification{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    //设置5秒之后
    NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:5];
    if (notification != nil) {
        // 设置推送时间(5秒后)
        notification.fireDate = pushDate;
        // 设置时区(此为默认时区)
        notification.timeZone = [NSTimeZone defaultTimeZone];
        // 设置重复间隔(默认0,不重复推送)
        notification.repeatInterval = 0;
        // 推送声音(系统默认)
        notification.soundName = UILocalNotificationDefaultSoundName;
        // 推送内容
        notification.alertBody = @"推送主体内容";
        //显示在icon上的数字
        notification.applicationIconBadgeNumber = 1;
        //设置userinfo 方便在之后需要撤销的时候使用
        NSDictionary *info = [NSDictionary dictionaryWithObject:@"name"forKey:@"key"];
        notification.userInfo = info;
        //添加推送到UIApplication
        UIApplication *app = [UIApplication sharedApplication];
        [app scheduleLocalNotification:notification];
    }
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。