iOS本地推送UILocalNotification

  本地通知主要是基于app本身定时器的行为。即使app在后台,也会发送本地通知。一个app只能有有限数量的预定通知,最多允许最近的64条通知,其余通知将会被系统忽略。

  推送通知的呈现效果:

  • 在屏幕顶部显示的一条横幅
  • 在屏幕中间弹出一个UIAlertView
  • 在锁屏界面显示一块横幅
  • 更新app图标的数字
  • 播放音效

1 在application: didFinishLaunchingWithOptions:方法中注册本地推送

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

     //启动应用时,将badge设为0

        let badge = application.applicationIconBadgeNumber

        if badge > 0 {

            application.applicationIconBadgeNumber = 0

     }

//注册本地通知
        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Badge, categories: nil))
        
        return true
  }

UIUserNotificationSettings的初始化方法 : 

    public convenience init(forTypes types: UIUserNotificationType, categories: Set<UIUserNotificationCategory>?)

其中UIUserNotificationType有四种类型:.None, .Badge, .Sound, .Alert。

2 创建本地通知UILocalNotification后,有两种方式可以添加到UIApplication中。

  (1) scheduledLocalNotifications,通过fireDate时间来发送通知

  (2) presentLocalNotificationNow, 会立刻发送通知,跟fireDate时间无关。

  添加一个本地通知,并在130s后取消该通知

override func viewDidLoad(){
     super.viewDidLoad() 
  
     let localNotif = UILocalNotification()    //推送的时间 localNotif.fireDate = NSDate(timeIntervalSinceNow: 10) //设置时区 localNotif.timeZone = NSTimeZone.defaultTimeZone() //设置重复间隔 localNotif.repeatInterval = .Minute //推送声音 localNotif.soundName = UILocalNotificationDefaultSoundName//系统默认声音
    
localNotif.soundName = “shake.wav”              //自定义文件
     //推送内容 
     localNotif.alertBody = "推送内容"

     //显示在icon上的红色圈中的数子
     localNotif.applicationIconBadgeNumber = 1

     //设置userinfo 方便在之后需要撤销的时候使用
    localNotif.userInfo = ["key1": "name1"]

     let app
= UIApplication.sharedApplication()
    
//添加到系统的本地推送列表
     app.scheduledLocalNotifications = [localNotif]

          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * 130.0 )), dispatch_get_main_queue()) {

              self.cancelLocalNotif()

         }

}

3 取消本地通知 cancelLocalNotification: 或者 cancelAllLocalNotifications

func cancalLocalNotif() {

     var
localNotif: UILocalNotification? let app = UIApplication.sharedApplication() let array = app.scheduledLocalNotifications if array != nil && array?.count > 0 { for notif in array! { let dict = notif.userInfo if dict != nil { let value = dict!["key1"] as? String ?? "" if value == "name1" { localNotif = notif break } } } } if localNotif != nil { app.cancelLocalNotification(localNotif!) }
}

4 如果接受到通知时,应用在后台,通知会通过alert,sound,badge方式来体现。点击通知后,会触发application:didReceiveLocalNotification:方法。

如果接受到通知时,应用在前台,则没有alert,sound,badge,但是收到通知时仍会触发application:didReceiveLocalNotification:方法。

如果本地通知只有badge,则启动app后,在application:didFinishLaunchingWithOptions的options字典中不包含UILocalNotification对象。

   func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
        

     //点击通知后,将badge设为0

        let badge = application.applicationIconBadgeNumber

        if badge > 0 {

            application.applicationIconBadgeNumber = 0

     }


        print(notification)
        print(notification.alertBody)
        let a = notification.userInfo
        if a != nil {
            print(a)
        }
        
    }

打印结果为:

<UIConcreteLocalNotification: 0x12e58db10>{fire date = 2016年8月9日 星期二 中国标准时间 下午4:27:58, time zone = Asia/Shanghai (GMT+8) offset 28800, repeat interval = NSCalendarUnitMinute, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = 2016年8月9日 星期二 中国标准时间 下午4:28:58, user info = {
    key1 = name1;
}}
Optional("推送内容")
Optional([key1: name1])
原文地址:https://www.cnblogs.com/muzijie/p/5753774.html