iOS笔记之通知

作者: 尽欢呀尽欢 | 来源:发表于2015-05-26 10:05 被阅读238次

    通知中心(NotificationCenter)和通知(UILocalNotification)是雷锋和雷峰塔的关系哦

    通知分为本地通知和远程通知

    本地通知就是你好久不用一个程序,它给你拉一条横幅写“部落里没有你臣妾好寂寞”;或者更典型的一个日历软件,到时间提醒你今天是乔帮主的忌日。(UILocalNotification)

    即:由本地应用程序发起的通知,一般是在应用程序处于后台或退出后,让iOS系统在指定时间通知用户的一种方式。

    远程通知就是你收到一条微信,在锁屏上显示的或在顶部导航栏显示的。(APNS)

    本地通知使用步骤:

    1. 创建本地通知对象(UILocalNotification)
    let notification = UILocalNotification()
    
    1. 设置处理通知的时间(fireDate属性)
    notification.fireDate = NSDate(timeIntervalSinceNow: 5)
    
    1. 配置通知的内容:通知主体,通知声音,图标数字
    notification.repeatInterval = NSCalendarUnit.CalendarUnitMinute//CalendarUnit是指一分钟/小时/周之后再发
    notification.alertBody = "通知主体内容!"
    notification.applicationIconBadgeNumber = 1//强迫症最受不了的小红点,图标数字1
    notification.soundName = "success.caf"
    
    1. 调用通知:

    按计划调度: scheduleLocalNotification(一般情况都是按计划调用)

    UIApplication.sharedApplication().scheduleLocalNotification(notification)
    

    立即调用: presentLocalNotification(一般不用)

    要注意从iOS8开始,应用想发通知,必须经过用户允许,否则通知无法发送。

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    //判断当前设备是否是IOS8
    if(UIDevice.currentDevice().systemVersion > 7.0){
    //向用户申请发通知的权限(参数可以允许:通知内容,通知声音,图标数字)
    let settings = UIUserNotificationSettings(forTypes:UIUserNotificationType.Alert | UIUserNotificationType.Sound | UIUserNotificationType.Badge, categories:nil)
    application.registerUserNotificationSettings(settings)
                 }
    
    }
    

    用户点击通知之后会进入我们的App,所以还需要

    1.取消红点
    func applicationWillEnterForeground(application: UIApplication) {
            println("应用程序从后台进入到了前台!")
            //取消应用程序消息图标
            application.applicationIconBadgeNumber = 0
        }
    //取消已有的通知
            UIApplication.sharedApplication().cancelAllLocalNotifications()
    

    相关文章

      网友评论

        本文标题:iOS笔记之通知

        本文链接:https://www.haomeiwen.com/subject/itsrqttx.html