gpt4 book ai didi

ios - 为什么我无法使用 swift 3 在 iOS 上获取本地通知?

转载 作者:行者123 更新时间:2023-11-30 12:32:02 24 4
gpt4 key购买 nike

在 Xcode 8.3 和 swift 3.1 上运行

下面是我在 AppDelegate.swift 中的代码

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

let center = UNUserNotificationCenter.current()

center.requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { granted, error in
if granted {
print("User accept notification。")
}
else {
print("User don't like receive any notification!")
}
})

let content = UNMutableNotificationContent()
content.title = "Will it rain?"
content.body = "It never rains in (Southern) California!"
content.sound = UNNotificationSound.default()

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "local_notification", content: content, trigger: trigger)

center.add(request)

return true
}

我在 iPhone 上构建并运行它,并会显示一条消息,询问我是否愿意接收任何通知,然后单击“接受”。

然后,什么也没有发生。

我希望它会显示来自本地的通知,其中包含一些文本“会下雨吗”,就像我的代码中一样。

最佳答案

您必须让您的 AppDelegate 采用 UNUserNotificationCenterDelegate

applicationDidFinishLaunching 方法中,添加此 center.delegate = self

然后实现这段代码:

extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert])
}
}

来自苹果文档:

To respond to the delivery of notifications, you must implement a delegate for the shared UNUserNotificationCenter object. Your delegate object must conform to the UNUserNotificationCenterDelegate protocol, which the notification center uses to deliver notification information to your app. A delegate is required if your notifications contain custom actions.

引用: https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SchedulingandHandlingLocalNotifications.html

https://developer.apple.com/reference/usernotifications/unusernotificationcenterdelegate

关于ios - 为什么我无法使用 swift 3 在 iOS 上获取本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43404756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com