iOS SDK 8 中的本地通知

本文详细介绍了iOS SDK 8中本地通知的使用方法,包括如何注册本地通知、设置不同类型的通知、添加本地通知及如何处理用户点击通知后的响应。同时提供了代码示例帮助开发者更好地理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 注册本地通知

iOS SDK 8 中的本地通知与之前的本地推送不同之处在于:iOS SDK 8中的本地通知也需要注册,而之前本地推送是不需要注册的。

if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
        
        //设置通知的类型: alert、icon's badge、sound
        UIUserNotificationSettings *userNotificationSettings
        = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert categories:nil];
        //注册本地通知,会向用户索取授权
        [[UIApplication sharedApplication] registerUserNotificationSettings:userNotificationSettings];
    }

调用注册本地通知的方法,无论用户是否授权,均会调用以下代理方法。

如果用户未给予授权,notificationSettings.types = UIUserNotificationTypeNone。

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {

    if (notificationSettings.types == UIUserNotificationTypeNone) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您未授权本app通知权限" message:@"建议在xxx打开通知权限......" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

此外可以调用以下方法判断用户是否授权了本地通知:

if ([UIApplication instancesRespondToSelector:@selector(currentUserNotificationSettings)]) {
        NSLog(@"settings:%@",[[UIApplication sharedApplication] currentUserNotificationSettings]);
    }

  • 添加本地通知

添加一个本地推送:

UILocalNotification *newNotification = [[UILocalNotification alloc] init];
    if (newNotification) {
        newNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
        newNotification.alertBody = @"小懒猪,起床啦!";
        newNotification.soundName = [NSString stringWithFormat:@"%@.caf", @"tips"];
        newNotification.alertAction = @"起床闹钟";
        newNotification.repeatInterval = NSWeekCalendarUnit;
        newNotification.userInfo = [NSDictionary dictionaryWithObject:@"起床闹钟" forKey:kString_notificationName];
        [[UIApplication sharedApplication] scheduleLocalNotification:newNotification];
    }

如果用户点击了本地通知的alert进入应用,或者应用运行在前台时本地通知触发(此时无论用户是否授权),均会调用以下代理方法。

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    NSString *notificationName = notification.userInfo[kString_notificationName];
    NSString *title = nil;
    if ([notificationName isEqualToString:@"起床闹钟"]) {
        title = @"现在起床了";
    } else if ([notificationName isEqualToString:@"吃饭闹钟"]) {
        title = @"现在吃饭了";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

同样也可以查看已经添加的本地通知:
[[UIApplication sharedApplication] scheduledLocalNotifications];



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值