Reputation: 731
I'm trying to use FCM for push notification . I follow the docs and I'm trying to use :
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instange ID: \(error)")
} else if let result = result {
print("Remote instance ID token: \(result.token)")
self.instanceIDTokenMessage.text = "Remote InstanceID token: \(result.token)"
}
}
as specified in the docs but I'm not sure where I should put it, should it be inside didFinishLaunchingWithOptions
?
I get this compilation error :
Static member 'instanceID' cannot be used on instance of type 'InstanceID'
Upvotes: 0
Views: 596
Reputation: 110
I am certain that a few people coming through here and experiencing this issue are not having their problem solved by the solution given by Kuldeep.
I had the same exact issue.
Inside didRegisterForRemoteNotificationsWithDeviceToken
instead of using the InstanceID.instanceID().instanceID
as suggested by the capacitor guide, do this.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DidRegisterForRemoteNotificationsWithDeviceToken.name()), object: Messaging.messaging().fcmToken )
}
The only difference from the standard didRegisterForRemoteNotificationsWithDeviceToken
is that we are using Messaging.messaging().fcmToken
.
Found solution on medium. You would expect this or at least a working version to be on the capacitor docs... It is up to you which guide you follow, I used all of capacitors guide but needed this to test notifications with the fcmToken. The medium guide has more about the fcmToken, so, depending on your use case it may be a good idea to look into this guide.
Upvotes: 1
Reputation: 4552
Add Observer in didFinishLaunchingWithOptions
.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
}
Call it inside didRegisterForRemoteNotificationsWithDeviceToken
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
self.connectToFcm()
}
Method
@objc func tokenRefreshNotification(_ notification: Notification) {
self.connectToFcm()
}
Create 1 function.
func connectToFcm() {
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instange ID: \(error)")
}
else {
print("FCM Token = \(String(describing: result?.token))")
print("Remote instance ID token: \(result.token)")
self.instanceIDTokenMessage.text = "Remote InstanceID token: \(result.token)"
}
}
}
Upvotes: 1