iosswiftswinject

Swinject returns nil because object is wrong registered


This is how I register object for FirebaseMessaging:

    container.register(Messaging.self) { _ in
        return Messaging.messaging()
    }

and then I need to use it:

    container.register(NotificationSchedulerable.self) { resolver in
        let userNotificationCenter = resolver.resolve(UNUserNotificationCenter.self)!
        let messaging = resolver.resolve(Messaging.self)! //unexpectadly found nil
        return NotificationScheduler(userNotificationCenter: userNotificationCenter, messaging: messaging)
    }

But I receive an error:

Swinject: Resolution failed. Expected registration: { Service: FIRMessaging, Factory: Resolver -> FIRMessaging } Available registrations: { Service: FIRMessaging, Factory: Resolver -> FIRMessaging, ObjectScope: graph } Fatal error: Unexpectedly found nil while unwrapping an Optional value: file ToolsAssembly.swift, line 72

Why it happens?


Solution

  • Maybe the problem is that you have to register a FIRMessaging instead Messaging

    https://firebase.google.com/docs/cloud-messaging/ios/client?hl=es

    Like this:

        container.register(FIRMessaging.self) { _ in
            return Messaging.messaging()
        }
    

    And then:

    container.register(NotificationSchedulerable.self) { resolver in
            let userNotificationCenter = resolver.resolve(UNUserNotificationCenter.self)!
            let messaging = resolver.resolve(FIRMessaging.self)! //unexpectadly found nil
            return NotificationScheduler(userNotificationCenter: userNotificationCenter, messaging: messaging)
        }