【问题标题】:iOS app crashes when using FirebaseApp.configure()iOS 应用程序在使用 FirebaseApp.configure() 时崩溃
【发布时间】:2019-12-05 23:55:01
【问题描述】:

我想在我的框架中使用 Firebase 云消息传递。但是我在代码中使用 FirebaseApp.configure 时,除了以下错误消息外什么都没有崩溃:

Message from debugger: Terminated due to signal 9

有人知道发生了什么吗?

我在 firebase 中创建了项目和应用,并将 GoogleService-Info.plist 添加到我的应用中。我可以收到推送通知抛出 APN。但我就是无法在 FCM 中注册。

这是 AppDelegate.swift 中的相关代码:

import MyFramework

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    MyFramework.shared.start()

    return true
}

这是我框架中的代码:

import UIKit
import UserNotifications
import FirebaseCore

public class MyFramework: NSObject {
    public static let shared = MyFramework()

    override private init() {}

    public func start() {
        UNUserNotificationCenter.current().delegate = self
        UIApplication.shared.registerForRemoteNotifications()

        let authorizationOptions: UNAuthorizationOptions = [.alert, .sound, .badge]
        UNUserNotificationCenter.current().requestAuthorization(options: authorizationOptions, completionHandler: { (granted, error) in
            if let _error = error {
                print(_error.localizedDescription)
            }

            guard granted else {
                return
            }
        })

        FirebaseApp.configure()
    }
}

【问题讨论】:

  • 是否添加了‍import firebaseMyFrameworkAppDelegate
  • 已编辑,再次查看帖子
  • 您的框架设置是否正确?我猜你正在使用 CocoaPods?
  • 不,我没有使用可可豆荚,我使用依赖项作为链接库。
  • 这里确实没有足够的代码来确切地知道问题出在哪里,但我注意到有两件事是你缺少import Firebase 以及初始化 Firebase 应该在 didFinishLaunchingWithOptions 中完成。

标签: ios swift firebase firebase-cloud-messaging


【解决方案1】:

AppDelegate 中使用此示例代码,如果解决问题,则将代码转移到自定义类。

import UIKit
import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    // Override point for customization after application launch.

    FirebaseApp.configure()

    // [START set_messaging_delegate]
    Messaging.messaging().delegate = self
    // [END set_messaging_delegate]

    registerForPushNotifications()

    return true
}

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.

    application.applicationIconBadgeNumber = 0
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken as Data
}

func registerForPushNotifications() {

    // iOS 10 support
    if #available(iOS 10, *) {

        UNUserNotificationCenter.current().delegate = self

        UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in
            // Enable or disable features based on authorization.

            print("Permission granted: \(granted)")
            guard granted else { return }
        }
        UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in

            switch setttings.soundSetting{
            case .enabled:

                print("enabled sound setting")

            case .disabled:

                print("setting has been disabled")

            case .notSupported:
                print("something vital went wrong here")
            }
        }

        UIApplication.shared.registerForRemoteNotifications()
    }
        // iOS 9 support
    else if #available(iOS 9, *) {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
        // iOS 8 support
    else if #available(iOS 8, *) {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
        // iOS 7 support
    else {
        UIApplication.shared.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
    }
  }
}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo

    completionHandler()
 }
}
// [END ios_10_message_handling]


extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")

    let dataDict:[String: String] = ["token": fcmToken]

    print(dataDict)

    //        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.
}
// [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]
}

这段代码对我来说是正确的。如果不工作检查其他的东西!

【讨论】:

  • 我知道使用Firebase Messaging的方法,我的问题是依赖管理,我正在编写框架,所以我不能在AppDelegate中使用FirebaseApp.configre。
猜你喜欢
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 2015-09-02
相关资源
最近更新 更多