最近在看《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才能正常發送通知。
反省一下本身,感受到如今還沒養成到官方的幫助文檔尋找答案的習慣,一遇到問題就習慣找度娘╭(╯^╰)╮