IOS编程第四版中 scheduleLocalNotification 不通知的坑

准备换个开发方向,花了血本买了台mbp。跟着Big Nerd Ranch 出版社的ios编程第四版,发现这本书采用的xcode和sdk太老,导致很多坑。不过新版好像12月份要出来了,亚马逊上可以预定。接下来我把我在第六章遇到的坑内容记录一下,希望也能帮到其他人。

本地提醒 scheduleLocalNotification 的坑

根据书本上的步骤写完后,在UIDataPicker上设置了提醒时间,调试窗口里NSLog相关信息也打印出来了,但是坑爹的事发生了,活活等了几分钟也没有出现提醒。然后我查看了官方自己的代码和我的没有什么区别。代码都是如下:

NSDate *date = self.dataPicker.date;
NSLog(@"Setting a reminder for %@",date);

UILocalNotification *note = [[UILocalNotification alloc] init];
note.alertBody = @"Hypnotize me!";
note.fireDate = date;

[[UIApplication sharedApplication] scheduleLocalNotification:note];

然后我就怀疑是不是SDK版本不一致导致的,我去文档里查了下,发现UIApplication sharedApplication下有这样一段说明:

Prior to scheduling any local notifications, you must call the registerUserNotificationSettings: method to let the system know what types of alerts, if any, you plan to display to the user.

也就是说我们在使用本地通之前需要使用registerUserNotificationSettings 方法向系统注册我们的通知,让系统知道我们通知的类型是什么。好了接下来我去找到 registerUserNotificationSettings方法。方法原型:

(void) registerUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings

其中的notificationSettings就是你需要的通知类型,所有的通知类型如下:

typedef enum UIUserNotificationType : NSUInteger {
UIUserNotificationTypeNone    = 0,
UIUserNotificationTypeBadge   = 1 << 0,
UIUserNotificationTypeSound   = 1 << 1,
UIUserNotificationTypeAlert   = 1 << 2,
} UIUserNotificationType;

我们需要的类型正好就是 UIUserNotificationTypeAlert 于是我们对教程代码作出如下修改:

NSDate *date = self.dataPicker.date;
NSLog(@"Setting a reminder for %@",date);

UILocalNotification *note = [[UILocalNotification alloc] init];
note.alertBody = @"Hypnotize me!";
note.fireDate = date;
#设置我们需要的本地通知类型
UIUserNotificationSettings *local = [UIUserNotificationSettings settingsForTypes:1 << 2 categories:nil];
#对通知进行注册,让系统知道
[[UIApplication sharedApplication] registerUserNotificationSettings:local];

[[UIApplication sharedApplication] scheduleLocalNotification:note];

完成以上步骤后就可以看见本地通知了,第一次运行通知的时候会弹出界面问你是否允许通知,后面都不会弹出这个界面了。这个坑让我认识到出本社教程只是起个指引,真正要学会的还是如何利用官方文档解决问题。

    原文作者:BigNerdCoding
    原文地址: https://segmentfault.com/a/1190000003942425
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞