在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(参数) 方法即可让系统弹出窗口.