我正在通过FCM开发消息通信。
但是有一个问题。在iPhone 6
版本12.4
,您通常可以获得设备令牌和FCM值。
但是,11.4
不会获取设备令牌值,也不会获取 FCM 令牌值。我不知道问题出在哪里。
应用委托.swift
import UIKit
import UserNotifications
import Firebase
import FirebaseMessaging
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
func registerAppForPushNotificaition(){
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
let inviteCategory = UNNotificationCategory(identifier: "Notification", actions: [], intentIdentifiers: [], options: UNNotificationCategoryOptions.customDismissAction)
let categories = NSSet(objects: inviteCategory)
center.delegate = self
center.setNotificationCategories(categories as! Set<UNNotificationCategory>)
center.requestAuthorization(options: [.sound, .badge, .alert], completionHandler: { (granted, error) in
if !(error != nil){
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
})
} else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types:[.sound , .alert , .badge] , categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler(.alert)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
// Override point for customization after application launch.
//create the notificationCenter
Messaging.messaging().delegate = self
FirebaseApp.configure()
//Register App For Push Notification
let center = UNUserNotificationCenter.current()
let inviteCategory = UNNotificationCategory(identifier: "Notification", actions: [], intentIdentifiers: [], options: UNNotificationCategoryOptions.customDismissAction)
let categories = NSSet(objects: inviteCategory)
center.delegate = self
center.setNotificationCategories(categories as! Set<UNNotificationCategory>)
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
application.registerForRemoteNotifications()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map{ String(format: "%02x", $0) }.joined()
Log.Info("Registration succeeded!")
Log.Info("Token: (token)")
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
Messaging.messaging().apnsToken = deviceToken
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
Log.Error("Error fetching remote instance ID: (error)")
} else if let result = result {
Log.Info("Remote instance ID token: (result.token)")
LocalStorage.set(result.token, "dacDeviceToken")
}
}
Messaging.messaging().shouldEstablishDirectChannel = true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
Messaging.messaging().apnsToken = deviceToken as Data
// print(deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
Log.Warning("Registration failed!")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(userInfo) {
Log.Info("fetchCompletionHandler")
completionHandler(UIBackgroundFetchResult.noData)
return
}
Log.Info("fetchCompletionHandler")
completionHandler(UIBackgroundFetchResult.newData)
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
Log.Info("fcmToken (fcmToken)")
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
Log.Info("remort (remoteMessage.appData)")
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
Log.Info("applicationWillResignActive")
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
Log.Info("applicationDidEnterBackground")
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
Log.Info("applicationWillEnterForeground")
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
Log.Info("applicationDidBecomeActive")
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
Log.Info("applicationWillTerminate")
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
print("Notification settings: (settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
@available(iOS 10, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let data = response.notification.request.content.userInfo
Log.Info(data)
guard
let aps = data[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String
else {
Log.Error("it's not good data")
return
}
completionHandler()
}
在 iPhone 12.4 上,FCM 令牌值在此处接收。iOS版本是一样的。
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map{ String(format: "%02x", $0) }.joined()
Log.Info("Registration succeeded!")
Log.Info("Token: (token)")
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
Messaging.messaging().apnsToken = deviceToken
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
Log.Error("Error fetching remote instance ID: (error)")
} else if let result = result {
Log.Info("Remote instance ID token: (result.token)")
LocalStorage.set(result.token, "dacDeviceToken")
}
}
Messaging.messaging().shouldEstablishDirectChannel = true
}
豆荚文件
# Pods for DeleteMe
pod 'SwiftSVG', '~> 2.0'
pod 'Toaster'
pod 'BigInt', '~> 4.0'
pod 'CryptoSwift'
pod 'RealmSwift'
pod 'web3.swift.pod', '~> 2.2.0'
pod 'Firebase'
pod 'Firebase/Messaging'
pod 'Firebase/Auth'
11.4 在苹果手机日志中
2019-10-02 13:39:01.964008+0900 test[1804:476574] - <AppMeasurement>[I-ACS036002] Analytics screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable screen reporting, set the flag FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist
2019-10-02 13:39:02.045557+0900 test[1804:476574] 6.9.0 - [Firebase/Core][I-COR000003] The default Firebase app has not yet been configured. Add `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your application initialization. Read more:
2019-10-02 13:39:02.099986+0900 test[1804:476574] 6.9.0 - [Firebase/Analytics][I-ACS023007] Analytics v.60102000 started
2019-10-02 13:39:02.102201+0900 test[1804:476574] 6.9.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2019-10-02 13:39:02.139092+0900 test[1804:476582] 6.9.0 - [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO. Follow the instructions at:
to ensure proper integration.
2019-10-02 13:39:02.231208+0900 test[1804:476536] [Graphics] UIColor created with component values far outside the expected range. Set a breakpoint on UIColorBreakForOutOfRangeColorComponents to debug. This message will only be logged once.
INFO: 2019-10-02 04:39:02 +0000 - <UI> AppDelegate.swift applicationDidBecomeActive(_:) [Line:225]
applicationDidBecomeActive
2019-10-02 13:39:02.371104+0900 test[1804:476581] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2019-10-02 13:39:02.373237+0900 test[1804:476581] [MC] Reading from public effective user settings.
但是,您无法在 iPhone 11.4 上的任何地方看到 FCM 令牌或设备令牌值的日志。你怎么能解决这个问题?
@Starsky是对的。这是一个错误,在我删除我的应用程序并重新启动设备后,问题就解决了。