在旧项目中,第一次安装应用程序或刷新令牌时,我已收到设备令牌。但是,现在我创建了一个新项目,并为注册设备令牌委托和请求权限编写了代码,但现在在4.2版本中未调用注册设备令牌。有人遇到过这个问题吗?如果是,解决方案是什么?
import UIKit
import FirebaseInstanceID
import GoogleMaps
import GooglePlaces
import UserNotifications
import FirebaseCore
import FirebaseMessaging
import Alamofire
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate,MessagingDelegate,CLLocationManagerDelegate {
var window: UIWindow?
let locationManager = CLLocationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let statusbar = UIApplication.shared.value(forKey: "statusBar") as? UIView {
statusbar.backgroundColor = UIColor.fromHexaString(hex: "feac1c")
}
UIApplication.shared.statusBarStyle = .lightContent
Fabric.with([Crashlytics.self])
let remoteNotif = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? NSDictionary
if remoteNotif != nil
{
}
else
{
print("Not remote")
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
GMSServices.provideAPIKey(google_url_links().google_mapKey)
GMSPlacesClient.provideAPIKey(google_url_links().google_mapKey)
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in
Messaging.messaging().delegate = self
})
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
NotificationCenter.default.addObserver(self, selector: #selector(appDelegate.tokenRefereshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
// Override point for customization after application launch.
return true
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print(remoteMessage.appData)
}
// func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
//
// print("Firebase registration token: \(fcmToken)")
// UserDefaults.standard.set(fcmToken, forKey: "DeviceToken")
//
//
// }
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
Messaging.messaging().apnsToken = deviceToken
//FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .none)
// Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
}
@objc func tokenRefereshNotification()
{
let refereshtoken = InstanceID.instanceID().token() ?? ""
print("token23123::::\(refereshtoken)")
UserDefaults.standard.set(refereshtoken, forKey: "deviceToken")
connectToFCM()
}
func connectToFCM()
{
guard InstanceID.instanceID().token() != nil else
{
return
}
Messaging.messaging().disconnect()
Messaging.messaging().connect { (error) in
if (error != nil)
{
print("error unable to connect\(String(describing: error))")
}
else
{
print("connect to fcm")
}
}
}
@objc func CheckInterntConnection()
{
let alert = UIAlertController(title: "", message: custom_message().error_internet, preferredStyle: UIAlertController.Style.actionSheet)
alert.addAction(UIAlertAction(title: custom_message().OK, style: UIAlertAction.Style.default, handler: nil))
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}
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.
}
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.
}
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.
}
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.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
答案 0 :(得分:2)
您也需要获取Firebase令牌
在AppDelegate类中声明一个变量。
var firebaseToken: String = ""
在您的didFinishLaunchingWithOptions
函数中调用这些方法
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
self.registerForFirebaseNotification(application: application)
Messaging.messaging().delegate = self
return true
}
在您的AppDelegate类中添加此功能。
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
func registerForFirebaseNotification(application: UIApplication) {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
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()
}
}
最后创建AppDelegate的扩展并添加这些功能
extension AppDelegate: MessagingDelegate, UNUserNotificationCenterDelegate {
//MessagingDelegate
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
self.firebaseToken = fcmToken
print("Firebase token: \(fcmToken)")
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("didReceive remoteMessage: \(remoteMessage)")
}
//UNUserNotificationCenterDelegate
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("APNs received with: \(userInfo)")
}
}
答案 1 :(得分:0)
您必须调用以下函数来获取fcm令牌,
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
UserDefaults.standard.set(fcmToken, forKey: "DeviceToken")
}
,然后将您的didFinishLaunchingWithOptions()
的appDelegate编辑为,
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
if(launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil){
}
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instance ID: \(error)")
} else if let result = result {
print("Remote instance ID token: \(result.token)")
}
}
Messaging.messaging().isAutoInitEnabled = true
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert,.sound] // .badge,
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert,.sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
Messaging.messaging().delegate = self
return true
}
答案 2 :(得分:0)
swift中的相同方法将帮助您跟踪令牌委托数据
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Unable to register for remote notifications: %@", error);
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the
//APNs device token can be paired to
// the FCM registration token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"APNs device token retrieved: %@", deviceToken);
// With swizzling disabled you must set the APNs device token here.
[FIRMessaging messaging].APNSToken = deviceToken;
}