這里說的通知不是我們平常說的NSNotificationCenter,而是一種推送信息.
本地推送是在不需要聯網的情況下發出的推送通知
經常用來定時提醒用戶,比如說鬧鐘.
下面看一下如何使用:
有三步:
- 創建本地通知對象
- 設置通知內容
- 調用通知
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// 1. 創建本地通知
let localNote = UILocalNotification()
// 2. 內容
// 發出通知的時間
localNote.fireDate = NSDate(timeIntervalSinceNow: 3)
localNote.alertBody = "這是一條本地通知"
// 重復的頻率. 枚舉值
localNote.repeatInterval = .Day
localNote.alertAction = "呵呵"
// 可以隨便寫,都會調用LaunchImage圖片
localNote.alertLaunchImage = "haha"
localNote.alertTitle = "通知"
// 通知聲音 系統的字符串
localNote.soundName = UILocalNotificationDefaultSoundName
// 設置
localNote.applicationIconBadgeNumber = 10
// 其他信息,這個可以在代理方法中獲取
localNote.userInfo = ["note" : "haha"]
// 3. 調用 UIApplication.sharedApplication().scheduleLocalNotification(localNote)
}
注意
在iOS8以上,需要獲取權限,在func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool中設置
if Double(UIDevice.currentDevice().systemVersion) >= 8.0 {
// Types可以設置的內容是個枚舉值
let setting = UIUserNotificationSettings(forTypes: [.Badge, .Alert, .Sound], categories: nil)
application.registerUserNotificationSettings(setting)
}
添加上面代碼,在第一次啟動應用時會進行選擇.
如果我們需要在點擊通知后做某些事情的話,需要在下面的代理方法里面寫
// 當程序進入前臺或在前臺時,執行該方法
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
debugPrint("接收到通知")
// 打印的是上面說的 localNote.userInfo
debugPrint(notification.userInfo)
// 不是處于前臺
if application.applicationState == .Inactive {
debugPrint("進行一些事件處理")
}
}
但是如果退出了應用,就不會執行上面的代理方法,這時點擊通知依然會啟動程序,這種情況需要在 didFinishLaunchingWithOptions 方法中獲取應用啟動方式,如果是
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if Double(UIDevice.currentDevice().systemVersion) >= 8.0 {
let setting = UIUserNotificationSettings(forTypes: [.Badge, .Alert, .Sound], categories: nil)
application.registerUserNotificationSettings(setting)
}
// 各種打開apple的方式,key是字符串常量,如果正常點擊圖標啟動的話launchOptions是一個空值nil
// 這里是判斷是否是通過本地通知打開
if ((launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey]) != nil) {
debugPrint("通過本地通知進入,處理事件") // 打印無效果
/*
// 由于重新啟動了程序無法驗證打印的信息,我們可以通過添加控件進行驗證
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.backgroundColor = UIColor.redColor()
window!.rootViewController?.view.addSubview(view)
}
*/
return true
}```