最近在看《iOS编程(第4版)》(就是Big Nerd Ranch用的那本教材)。这本书写的不错,推荐一下,写的很细致,按部就班,不能不赞一下外国人写书的思路,确实跟国人不一样。以前学Android的时候,看了《Android Programming The Big Nerd Ranch Guide》,虽然全英文看得有点慢,可是慢慢看以为颇有意思,对于有了必定基础的初学者,收获很大。回到这本国人翻译的iOS编程,中文翻译过来的一些词汇有点拗口,我表示有点记不住╭(╯^╰)╮,看到大段中文的时候,耐心不足。编程
言归正传,今天看到一处,关于添加Local Notification的,本身用XCode6进行构建的时候,出现了错误。app
程序是在一个按钮的点击事件的响应方法中,注册本地通知。下面就是ViewController.m中的按钮响应方法。ide
1 -(IBAction)addReminder:(id)sender 2 { 3 NSDate *date=self.datePicker.date; 4 UILocalNotification *note=[[UILocalNotification alloc] init]; 5 note.alertBody=@"Hypnotize me!"; 6 note.fireDate=date; 7 [[UIApplication sharedApplication] scheduleLocalNotification:note]; 8 }
构建以后,点击模拟器应用中的Button,没有弹出通知,而XCode却给出了下面的Debug信息。ui
2015-07-02 10:21:31.538 HypnoNerd[1185:42048] Attempting to schedule a local notification <UIConcreteLocalNotification: 0x7fcd5be826b0>{fire date = Thursday, July 2, 2015 at 10:21:29 AM China Standard Time, time zone = (null), repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = (null), user info = (null)} with an alert but haven't received permission from the user to display alerts
确认代码输入没有错,那么为何会弹出这样的信息呢?抓住提示信息中的最后一句,有个关键词“permission”,瞬间感受和写Android应用时候用到的permission很像呀。spa
上网查了一下,看到这篇文章“iOS8系统下的没法弹出通知”,说是iOS8系统变动了注册方法(没错,我用的SDK是iOS 8.3)。用了做者的方法,确实解决了问题。.net
不过做者只写了解决办法,对于缘由没有多作解释。翻译
我到XCode的SDK Guide帮助文档 Local and Remote Notification Programming Guide: Registering, Scheduling, and Handling User Notificationscode
中,找到了Apple关于这个问题的说明。blog
In iOS 8 and later, apps that use either local or remote notifications must register the types of notifications they intend to deliver. The system then gives the user the ability to limit the types of notifications your app displays. The system does not badge icons, display alert messages, or play alert sounds if any of these notification types are not enabled for your app, even if they are specified in the notification payload.事件
在iOS8以及更高版本的iOS系统中,若是要用本地通知或者远程通知,必需要注册通知的类型,注册成功以后,系统才会给予用户传递通知(显示通知)的权限。
1 UIUserNotificationType type=UIUserNotificationTypeAlert; 2 UIUserNotificationSettings *settings=[UIUserNotificationSettings settingsForTypes:type categories:nil]; 3 [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
在ApplicationDelegate中注册通知以后,第一次运行App,会弹出一个对话框,询问用户是否容许这个App发送通知,用户点击“确认”后,App才能正常发送通知。
反省一下本身,感受到如今还没养成到官方的帮助文档寻找答案的习惯,一遇到问题就习惯找度娘╭(╯^╰)╮