zoukankan      html  css  js  c++  java
  • iOS8无法弹出本地通知?

    最近在看《iOS编程(第4版)》(就是Big Nerd Ranch用的那本教材)。这本书写的不错,推荐一下,写的很细致,循序渐进,不能不赞一下外国人写书的思路,确实跟国人不同。之前学Android的时候,看了《Android Programming The Big Nerd Ranch Guide》,虽然全英文看得有点慢,但是慢慢看觉得很有意思,对于有了一定基础的初学者,收获很大。回到这本国人翻译的iOS编程,中文翻译过来的一些词汇有点拗口,我表示有点记不住╭(╯^╰)╮,看到大段中文的时候,耐心不足。

    言归正传,今天看到一处,关于添加Local Notification的,自己用XCode6进行构建的时候,出现了错误。

    程序是在一个按钮的点击事件的响应方法中,注册本地通知。下面就是ViewController.m中的按钮响应方法。

    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信息。

    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很像呀。

    上网查了一下,看到这篇文章“iOS8系统下的无法弹出通知”,说是iOS8系统变更了注册方法(没错,我用的SDK是iOS 8.3)。用了作者的方法,确实解决了问题。

    不过作者只写了解决办法,对于原因没有多做解释。

    我到XCode的SDK Guide帮助文档 Local and Remote Notification Programming Guide: Registering, Scheduling, and Handling User Notifications

    中,找到了Apple关于这个问题的说明。

    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才能正常发送通知。

    检讨一下自己,感觉到现在还没养成到官方的帮助文档寻找答案的习惯,一遇到问题就习惯找度娘╭(╯^╰)╮

  • 相关阅读:
    OO助教总结
    OO2019第四单元作业总结
    OO2019第三单元作业总结
    OO2019第二单元作业
    OO2019第一单元作业总结
    OO第一单元作业总结
    BUAA_OO_2020_Unit4_Summary
    BUAA_OO_2020_Unit3_Summary
    BUAA_OO_2020_Uint2_Summary
    闫金柱-OO第一单元总结
  • 原文地址:https://www.cnblogs.com/tt2015-sz/p/4615551.html
Copyright © 2011-2022 走看看