本地推送(UILocalNotification)和遠程推送其目的都是要提醒用戶去做某件事情乓诽,其本質區(qū)別有兩點:(1)是否需要聯(lián)網?(2)觸發(fā)者是誰?簡單來說,本地推送是由用戶(App使用者)觸發(fā),不需要聯(lián)網,類似的比如ToDoList榄鉴,一對一推送;而遠程推送觸發(fā)者是App運營者蛉抓,為了宣傳產品提高用戶粘合度庆尘,推送形式單對多,需要聯(lián)網巷送。
Step1:iOS8之后推送要求必須注冊App支持的用戶交互類型驶忌,注冊代碼和遠程推送注冊代碼相同如下
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Badge,UIUserNotificationType.Alert,UIUserNotificationType.Sound]categories: [category]))
如果沒有特殊需求(比如使用到UIMutableUserNotificationAction)可以將后面的categories設置為nil
在介紹下一步之前有必要說一下UILocalNotification的基本屬性便于大家理解使用
屬性名 | 類型 | 備注 | 英文原版 |
---|---|---|---|
fireDate | NSDate? | 代表推送的啟動時間 | timer-based scheduling |
timeZone | NSTimeZone? | 說明設置的fireDate在哪個時區(qū) | the time zone to interpret fireDate in |
repeatInterval | NSCalendarUnit | 重復次數 | nil |
repeatCalendar | NSCalendar? | 重復推送時間 | nil |
alertBody | String? | 通知內容 | pass a string or localized string key to show an alert |
alertAction | String? | 解鎖滑動時的事件 | used in UIAlert button or 'slide to unlock...' slider in place of unlock |
soundName | String | 消息推送提示聲音 | name of resource in app's bundle to play or UILocalNotificationDefaultSoundName |
alertLaunchImage | String? | 啟動圖片,設置此字段點擊通知時會顯示該圖片 | used as the launch image (UILaunchImageFile) when launch button is |
alertTitle | String? | 消息標題笑跛,默認無 | defaults to nil. pass a string or localized string key |
applicationIconBadgeNumber | Int | App icon的角標 | 0 means no change. defaults to 0 |
userInfo | [NSObject : AnyObject]? | 自定義參數 | nil |
Step2:添加推送通知
@IBAction func sendLocalNotification(sender: UIButton) {
let localNotification = UILocalNotification();
//觸發(fā)通知時間
localNotification.fireDate = NSDate(timeIntervalSinceNow:5);
//重復間隔
// localNotification.repeatInterval = kCFCalendarUnitMinute;
localNotification.timeZone = NSTimeZone.defaultTimeZone();
//通知內容
localNotification.alertBody = "本地消息推送測試";
localNotification.applicationIconBadgeNumber = 1;
localNotification.soundName = UILocalNotificationDefaultSoundName;
//通知參數
localNotification.userInfo = ["message": "本地消息"];
localNotification.category = "categoryIdentifier";
UIApplication.sharedApplication().scheduleLocalNotification(localNotification);
}
至此付魔,本地推送已經完成,但需要說明的是飞蹂,如果推送發(fā)生時几苍,App處于Foreground會直接調用
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification)
如果App處于Background狀態(tài)時,此時觸發(fā)推送會在通知欄產生一條消息陈哑,當你點擊推送消息后才會觸發(fā)上面的方法擦剑。
如果你想實現(xiàn)特殊的消息推送,比如快速點贊芥颈、回復等,可使用UIMutableUserNotificationAction定義不同的action并指定其唯一的identifier赚抡,因為無需打開App可直接將action的activationMode設置為Background爬坑,處理函數為:
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void){
if identifier == "yourIdentifier"{
//do something..
}else{
//else do...
}
completionHandler()
}