iOS 应用在前台时显示通知

背景:

在iOS应用中,当应用在前台运行时,是不会默认弹出通知的。这是iOS的设计决定,以避免用户在使用应用的过程中被打扰。然而,如果你希望在应用在前台的时候也能收到通知,你可以在你的应用代码中进行一些修改。

添加代理

  1. 在AppDelegate的didFinishLaunchingWithOptions:方法中设置通知中心的代理

  2. 在你的AppDelegate中实现userNotificationCenter(_:willPresent:withCompletionHandler:)方法。

    public func setNotifiAuth() {
    let center = UNUserNotificationCenter.current()
    center.delegate = self
    center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
    if granted == true {
    dePrint("允许通知")
    } else {
    dePrint("不允许通知")
    }
    }
    }

    extension LocalNotification: UNUserNotificationCenterDelegate {
    // 前台显示弹窗
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
    return .alert
    }
    }

相关推荐
kevinli7 小时前
available没你想象中的可靠
ios·编译原理
CodeJourney_J1 天前
如何通过SMB协议实现手机共享电脑文件
windows·ios·smb
ipad协议开发1 天前
企业微信iPad协议接口深度解析:技术原理、应用场景与开发实战
ios·企业微信·ipad
千里马-horse2 天前
Building a Simple Engine -- Mobile Development -- Platform considerations
android·ios·rendering·vulkan
systeminof2 天前
全新MacBook发布:苹果公司将 iPhone 芯片带入笔记本时代
ios·iphone
pop_xiaoli2 天前
effective-Objective-C 第四章阅读笔记
笔记·ios·objective-c·cocoa·xcode
前端不太难3 天前
Flutter 适合什么团队?RN / iOS 各自的边界在哪?
flutter·ios
带娃的IT创业者3 天前
解密OpenClaw系列10-OpenClaw系统要求
人工智能·macos·ios·objective-c·ai智能体·智能体开发·openclaw
systeminof3 天前
iOS 26.4 更新前瞻:Siri 架构级重构与上线时间预测
ios·重构