gpt4 book ai didi

ios - Swift FIRMessaging 在注册时发送推送通知请求

转载 作者:搜寻专家 更新时间:2023-11-01 06:18:05 25 4
gpt4 key购买 nike

我想知道如何在用户注册为我的应用程序用户之后而不是在用户打开我的应用程序时用众所周知的“应用程序”想向您发送推送通知来提示用户默认应用程序(甚至不是用户)。

我该怎么做?我以为你只会在 appDelegate.swift 中配置推送通知设置?提前致谢!

最佳答案

您可以在任何地方请求推送通知的权限,实际上如果您的应用程序有登录页面,那么在登录后您肯定需要这样做。

您首先需要将请求权限的代码放在 AppDelegate.swift 的函数中。

func registerUserNotification() {


if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]

UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (bool, error) in

UNUserNotificationCenter.current().delegate = self

if (error == nil) {
// its required for iOS 11 to avoid getting warning about "UI API called on a background thread"
DispatchQueue.main.async {

UIApplication.shared.registerForRemoteNotifications()

}
}

})


} else {
if UIApplication.shared.responds(to: #selector(UIApplication.registerUserNotificationSettings(_:))) {

let types:UIUserNotificationType = ([.alert, .badge, .sound])
let settings:UIUserNotificationSettings = UIUserNotificationSettings(types: types, categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()

}

}
}

注意:另外不要忘记导入 UserNotifications 以便能够使用适用于 iOS 10 的最新 SDK。

在任何 View Controller 中,您需要引用应用委托(delegate)并调用该函数:

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.registerUserNotification()

更新 1:

您需要按如下方式实现 UNUserNotificationCenter 的委托(delegate),将以下代码放在 AppDelegate 的末尾,超出类范围 (}),这是 iOS 10 所必需的:

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {


// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

print("Userinfo \(notification.request.content.userInfo)")



}


func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

print("Userinfo \(response.notification.request.content.userInfo)")



}



}

关于ios - Swift FIRMessaging 在注册时发送推送通知请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39860301/

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