在APP處於后台時接收到通知會在頂部滑下一個通知框,而APP處於前台時則沒有任何提示.
如何讓APP處於前台時也有后台這種效果呢?
下面上代碼.
首先你先設定一下代理 在AppDelegate中實現以下代碼.(你也可以在你需要的地方設定.但你必須保證對象一直存在.在appdelegate中測試相對穩妥)
*******************************************************************
let center = UNUserNotificationCenter.current()// 獲取當前通知中心
center.requestAuthorization(options: [.alert, .sound, .badge]) { (isSuccess, error) in// 設定通知提示
print("regist is \(isSuccess && error == nil ? "success" : "failure")")// 判斷是否配置成功
}
center.delegate = self// 設定代理.注意代理要遵守UNUserNotificationCenterDelegate
*******************************************************************
下面是代理方法回調. 后台通知大家都懂,這里僅演示前台接收.
注意下面桔紅色部分代碼.你實現了這句代碼.就可以使APP在前台時也彈出通知框.
*******************************************************************
//MARK:---- UNUserNotificationCenterDelegate ----
// 當程序在前台時收到通知會觸發
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(UNNotificationPresentationOptions.alert)
// 如果你需要多個參數則傳 數組 例 completionHandler([.alert, .sound, .badge])
}
// 注意OC則在以下方法中實現
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
completionHandler(UNNotificationPresentationOptionAlert)
// 如果你需要多個參數則用 | 分開 例 completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert)
}
*******************************************************************
最后發送一個本地通知,讓APP保持在前台三秒后即會彈出窗口.
*******************************************************************
// 發送一個本地通知
func sendNotice() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "title"
content.subtitle = "subtitle"
content.body = "body"
content.categoryIdentifier = "categoryIdentifier"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
let req = UNNotificationRequest.init(identifier: "本地通知", content: content, trigger: trigger)
center.add(req) { (error) in
print("******\(error)******")
}
}
*******************************************************************
總結:在接收到通知的回調方法中實現 completionHandler(參數) 方法即可讓系統彈出窗口.