在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(参数) 方法即可让系统弹出窗口.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?