我正在 Swift 中进行测试,以使用 Firebase 发送通知,总体来说它可以正常工作。当我向一个用户发送通知时,我需要该用户的设备令牌。我猜这和UUID不一样? 通过创建帐户,我喜欢通过在 webview 页面的 url (GET) 中添加 id 来将此 id 存储在数据库中。我怎样才能做到这一点?有解决办法吗?
这是 ViewController.swift 代码
import UIKit
import WebKit
class ViewController: UIViewController {
let webView=WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(webView)
guard let url = URL(string: "**https://myurl.be/app.php?device=CODE**")else {
return
}
webView.load(URLRequest(url:url))
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
webView.frame = view.bounds
}
}
AppDelegate.swift
import UIKit
import FirebaseCore
import FirebaseMessaging
import UserNotifications
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
let gcmMessageIDKey = "gcm.Message_ID"
var deviceTokenString: String?
var testString = "test"
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("===== deviceTokenString =====")
print(deviceTokenString ?? "nok")
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
// Push Notifications
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: { _, _ in }
)
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
Messaging.messaging().delegate = self
return true
}
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>)
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions)
-> Void) {
let userInfo = notification.request.content.userInfo
print(userInfo)
completionHandler([[.alert, .sound]])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
print(userInfo)
completionHandler()
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult)
-> Void) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: fcmToken))")
let dataDict: [String: String] = ["token": fcmToken ?? ""]
NotificationCenter.default.post(
name: Notification.Name("FCMToken"),
object: nil,
userInfo: dataDict
)
}
func application(_application:UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
print (deviceToken.map({String(format: "%02x", $0 )}).joined()) //optie1
print (deviceToken.reduce(""){ $0 + String (format: "%02.2hhx", $1)}) //optie2
print (deviceToken.reduce(""){ $0 + String (format: "%.2x", $1)}) //optie3
}
}
希望能找到解决办法。
如果我正确理解你的问题,我不是100%确定,但是..
首先...在存储
deviceToken
时,根据 Apple 的文档,您可能希望每次调用 UIApplication.registerUserNotificationSettings(_:)
方法时都将其发送到服务器。
这是一个好主意,因为正如他们所说:
重要 切勿在本地存储中缓存设备令牌。 APNs 问题 当用户从备份恢复设备时,当用户 在新设备上安装您的应用程序,并且当用户重新安装该应用程序时 操作系统。每次询问时您都会获得一个最新的令牌 系统提供令牌。
您可以在这里进行:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
self.sendDeviceTokenToServer(data: deviceToken)
}