我有以下AppDelegate.swift文件,该文件导致以下错误和应用程序崩溃,我对如何解决此问题一无所知。
我的Firebase设置和Apple配置文件正确,我也下载了“ GoogleServices-Info.plist”,并且捆绑包ID正确。
无法与FCM我的错误连接。可选(错误域= com.google.fcm代码= 501“(空)”) 43字节 dataPaddingRequired 处置
import UIKit
import DropDown
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging
import SwiftyJSON
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var userID: String = ""
var token: String = ""
private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.setupWindows()
if Common.sharedInstance.GetObjectInUserDefault(key: kToken) == nil {
self.token = ""
} else {
self.token = Common.sharedInstance.GetObjectInUserDefault(key: kToken)! as! String
}
if Common.sharedInstance.GetObjectInUserDefault(key: kUserId) == nil {
self.userID = ""
} else {
self.userID = Common.sharedInstance.GetObjectInUserDefault(key: kUserId)! as! String
}
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
let center = UNUserNotificationCenter.current()
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
center.requestAuthorization(options: authOptions, completionHandler: { (comppleted, error) in
print(error ?? "No error")
if error == nil {
center.delegate = self as! UNUserNotificationCenterDelegate
FirebaseApp.configure()
Messaging.messaging().delegate = self as! MessagingDelegate
application.registerForRemoteNotifications()
}
})
} else {
FirebaseApp.configure()
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
Messaging.messaging().delegate = self as! MessagingDelegate
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: NSNotification.Name.InstanceIDTokenRefresh,
object: nil)
DropDown.startListeningToKeyboard()
DropDown.appearance().textColor = UIColor.black
DropDown.appearance().textFont = UIFont.systemFont(ofSize: 15)
DropDown.appearance().backgroundColor = UIColor.white
DropDown.appearance().selectionBackgroundColor = UIColor.lightGray
DropDown.appearance().cellHeight = 60
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
// var tokenString = ""
//
// for i in 0..<deviceToken.count {
// tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
// }
//
// //Tricky line
// InstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
// print("Device Token:", tokenString)
Messaging.messaging().apnsToken = deviceToken
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
//print("Message ID: \(userInfo["gcm.message_id"]!)")
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}
// Print full message.
print("%@", userInfo)
Messaging.messaging().appDidReceiveMessage(userInfo)
// guard let userInfo_ = Common.sharedInstance.GetObjectInUserDefault(key: kUserInfo) as! [String: Any]? else {
// return
// }
//
// let json = JSON(userInfo_)
//
// guard let token = Common.sharedInstance.GetObjectInUserDefault(key: kToken) as? String else {
// return
// }
// if userInfo_["user_id"] != nil && (userInfo_["user_id"] as! String?) != json["user_id"].string {
// return
// }
if let userIDSendNotificationFrom = userInfo["user_id_from"] as? String {
Delay(second: 1, clousure: {
if let nv = self.window?.rootViewController as? UINavigationController? {
let vc = ProfileViewController(shouldShowNavigation: true)
vc.userIDToView = userIDSendNotificationFrom
nv!.pushViewController(vc, animated: true)
}
})
}
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
print("Registered notification setting")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("didFailToRegisterForRemoteNotificationsWithError: \(error)")
}
func application(_ application: UIApplication, didFailToContinueUserActivityWithType userActivityType: String, error: Error) {
}
// [START refresh_token]
func tokenRefreshNotification(notification: NSNotification) {
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
guard let refreshedToken = InstanceID.instanceID().token() else {
return
}
guard let userID = Common.sharedInstance.GetObjectInUserDefault(key: kUserId) as? String else {
return
}
guard let token = Common.sharedInstance.GetObjectInUserDefault(key: kToken) as? String else {
return
}
print("InstanceID token: \(refreshedToken)")
WebServiceAPI.sharedInstance.sendFirebaseToken(token: token, userID: userID, firebaseToken: refreshedToken).subscribe(onNext: { (respondData) in
}, onError: { (error) in
}, onCompleted: {
}, onDisposed: {
})
}
// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() {
Messaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM My Error. \(error)")
} else {
print("Connected to FCM.")
}
}
}
// [END connect_to_fcm]
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
let _ = WebServiceAPI.sharedInstance.getUserInfo(token: self.token, userID: self.userID, onlineStatus: 1).subscribe()
}
// [START disconnect_from_fcm]
func applicationDidEnterBackground(_ application: UIApplication) {
//Messaging.messaging().shouldEstablishDirectChannel
print("Disconnected from FCM.")
}
// [END disconnect_from_fcm]
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.
let _ = WebServiceAPI.sharedInstance.getUserInfo(token: self.token, userID: self.userID, onlineStatus: 0).subscribe(onCompleted: {
})
}
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 applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
//MARK: function
func setupWindows() {
let window = UIWindow()
window.frame = UIScreen.main.bounds
var vc:UIViewController = SplashViewController()
let rootVC = UINavigationController(rootViewController: vc)
window.rootViewController = rootVC
rootVC.isNavigationBarHidden = true
if Common.sharedInstance.GetObjectInUserDefault(key: kUserId) != nil
&& Common.sharedInstance.GetObjectInUserDefault(key: kToken) != nil {
vc = MainViewController()
rootVC.pushViewController(vc, animated: false)
}
self.window = window
window.makeKeyAndVisible()
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
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["gcm.message_id"] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
if let userIDSendNotificationFrom = userInfo["user_id_from"] as? String {
Delay(second: 1, clousure: {
if let nv = self.window?.rootViewController as? UINavigationController? {
let vc = ProfileViewController(shouldShowNavigation: true)
vc.userIDToView = userIDSendNotificationFrom
nv!.pushViewController(vc, animated: true)
}
})
}
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler([])
}
}
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
connectToFcm()
guard let refreshedToken = InstanceID.instanceID().token() else {
return
}
guard let userID = Common.sharedInstance.GetObjectInUserDefault(key: kUserId) as? String else {
return
}
guard let token = Common.sharedInstance.GetObjectInUserDefault(key: kToken) as? String else {
return
}
print("InstanceID token: \(refreshedToken)")
WebServiceAPI.sharedInstance.sendFirebaseToken(token: token, userID: userID, firebaseToken: refreshedToken).subscribe(onNext: { (respondData) in
}, onError: { (error) in
}, onCompleted: {
}, onDisposed: {
})
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
}