通知中心(NotificationCenter)和通知(UILocalNotification)是雷鋒和雷峰塔的關系哦
通知分為本地通知和遠程通知
本地通知就是你好久不用一個程序,它給你拉一條橫幅寫“部落里沒有你臣妾好寂寞”;或者更典型的一個日歷軟件,到時間提醒你今天是喬幫主的忌日。(UILocalNotification)
即:由本地應用程序發起的通知,一般是在應用程序處于后臺或退出后,讓iOS系統在指定時間通知用戶的一種方式。
遠程通知就是你收到一條微信,在鎖屏上顯示的或在頂部導航欄顯示的。(APNS)
本地通知使用步驟:
- 創建本地通知對象(UILocalNotification)
let notification = UILocalNotification()
- 設置處理通知的時間(fireDate屬性)
notification.fireDate = NSDate(timeIntervalSinceNow: 5)
- 配置通知的內容:通知主體,通知聲音,圖標數字
notification.repeatInterval = NSCalendarUnit.CalendarUnitMinute//CalendarUnit是指一分鐘/小時/周之后再發
notification.alertBody = "通知主體內容!"
notification.applicationIconBadgeNumber = 1//強迫癥最受不了的小紅點,圖標數字1
notification.soundName = "success.caf"
- 調用通知:
按計劃調度: 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()