我将应用程序开发为Webview。并成功配置了Firebase推送通知。消息传递良好。
但是现在我希望将设备令牌插入URL。通过它我可以根据令牌发送味精。
我在Appdelegate.swift中编写此代码
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map {String (format: "%02.2hhx", $0)}.joined()
print("Token : \(token)")
let preferences = UserDefaults.standard
preferences.setValue(token, forKey: "token")
preferences.synchronize()
}
//Changes
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError
error: Error) {
// Try again later.
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
//Saving fcmToken to pass to the url
//Bhaskar Changes
let preferences = UserDefaults.standard
preferences.setValue(fcmToken, forKey: "token")
preferences.synchronize()
let token = Messaging.messaging().fcmToken
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Message Data", remoteMessage.appData)
}
以及Viewcontroller.swift中的此代码
override func viewDidLoad() {
super.viewDidLoad()
//Retrieving the fcmToken
let prefs = UserDefaults.standard
let token = prefs.string(forKey: "token")
//?token= \(token as Optional)&device=ios
print("Token accessed : \(String(describing: token))")
webView.load(URLRequest(url: URL(string: "https://instaglamexpress.com/app/customer/?device=ios&token=\(String(describing: token))")!))
}
但是每次我运行程序时。令牌未存储到令牌变量中。它显示“无”。
我遵循正确的程序吗??
请帮我解决实际问题。
答案 0 :(得分:0)
也许您忘了以这种方式添加Messaging.messaging().delegate = self
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String)
永远不会被调用。