Retrieve the app push token from the device automatically in swift iOS - ios

Is it possible to get a device token (push token) automatically or without registering for push notification in iOS Swift?
Currently, we are getting device token while registering for push notifications:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
...
}

It's not possible. We can not retrieve the app push token from the device automatically or without registering for push notification in swift iOS

Related

iOS push notification: how to store push notification payload when application is kill or terminate in swift?

I am sending multiple push notification using firebase. My application getting all notification. Now how to store all push notifications data in user default when application is killed or terminate?
How to store all push notifications data when application is killed and the user click one push notification from all notification?
Your app is not getting invoked just with a push notifications. What you receive in the Notification tray is handled by iOS directly and the content of the push notification, specifically what is inside aps key of the Notification body is used to populate the content you see in the notification tray.
The app will not get invoked just because you received a push notification if the app is in suspended or killed state.
Unless of course your apns-push-type is set as background and content-available = 1 in your notification.
The call would go to
application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
Where you may process the contents as required by the app.
To detect if the app was launched from a Notification,
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
if let dict = launchingOptions?[.remoteNotification]{
//App launched from Notification
if let userInfo = dict as? [AnyHashable:Any]{
//Do what your app requires with the notification using the userInfo.
}
}
}

How to fix 'Multiple push notification' error in swift?

I'm going through process of adding push notification on my iOS app by following a book and some docs on push notification.
Push notification was working fine for few days and then all of a sudden I started getting 3 push notification at a time and then it gradually increased to 7.
// this function is called from didFinishLaunchingWithOptions function
func requestForNotification(_ application: UIApplication){
UNUserNotificationCenter.current().requestAuthorization(options: [.badge,.sound,.alert]) { (granted, _) in
guard granted else {return}
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.reduce(""){$0 + String(format: "%02x",$1) }
sendTokenToService(token: token)
print("device token is:::::::::: \(token)")
}
//Send token to local server
func sendTokenToService(token:String){
var params = [String:AnyObject]()
params["token"] = token as AnyObject
APIManager.shared.request(apiRouter: APIRouter.init(endpoint: .addAdminToken(param: params))) { (response, success) in
if success, let response = response["response"] {
print(response)
}
}
}
registerForRemoteNotifications() is being called only once but I found this on apple's official docs:
registerForRemoteNotifications() method: UIKit might call it in other rare circumstances. For example, UIKit calls the method when the user launches an app after having restored a device from data that is not the device’s backup data. In this exceptional case, the app won’t know the new device’s token until the user launches it.
Any idea how to resolve this issue ?
Push notifications are delivered once per device token. If you have access to your push notification server (or push provider if you are not managing it yourself), you can verify that is the case. When you are building the app and installing on a device, the new build will most likely be generating a new token. This also happens when the user uninstalls/installs the app. This could be the reason you're getting multiple notifications. Apple is supposed to invalidate old device tokens and send feedback back to your server. For more information on how Apple sends you feedback, here's a link to their Apple APNS docs.

How to switch push notification providers without re-prompting to enable push notifications?

There are many third party push notification providers like Appboy (Braze), Localytics, Urban Airship, etc. Our app is in production using "Provider A" but we are switching to "Provider B." Fresh installations get push notifications, but upgrade installations do not. Upon inspection it looks like didRegisterForRemoteNotificationsWithDeviceToken isn't called. How can push be enabled without having to re-prompt the user?
It is enough to call registerForRemoteNotifications in didFinishLaunchingWithOptions. It will trigger didRegisterForRemoteNotificationsWithDeviceToken or didFailToRegisterForRemoteNotificationsWithError callback if they've opted-in. The best part is that the callbacks are triggered if they opt-in sometime in the future (Assuming they've been prompted in-app at least once via registerUserNotificationSettings).
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//...
UIApplication.shared.registerForRemoteNotifications()
//...
}
See:
iOS 8 Remote notifications - When should I call registerForRemoteNotifications()?

iOS Firebase Push Notifications received to first token only, after token changes no longer received

edit: Updating question with new information.
So there's a number of questions out there about Firebase notifications not being received but I've not found one quite like this.
I've recently switched over from using the old p12 APNs certificates to the glorious new p8, and uploaded it to all of my projects on Firebase v4.0.0.
What I'm seeing is, when I do a fresh install of any of my projects, I can send & receive push notifications fine. But after some time, the token changes - and it just stops working - Firebase says "message sent successfully" but no message is received.
Weirdly - my app still receives push notifications to the previous Firebase token, while the new one reported by Firebase isn't working.
Following the advice at Debugging Firebase Cloud Messaging on iOS, I happily debugged the morning away:
Are there any error messages coming back from my Postman firebase attempts? Nope, success:1 every time
Am I getting pushes with app in the background, foreground or neither? Neither.
Are my AppDelegate remote notification registration attempts working successfully? Yes.
Can I directly send a message over APNs, using the new .p8 file? Yes (thanks to this). Messages are being received when I send them directly over APNs just fine!
In the Firebase console, if I send a message to all devices in a project, I receive the message to all devices. But if I try to limit it to my debug device via its FCM token, I get nothing.
So there's one last link that's just not working - appearing to work perfectly for new installs and then bombing after some amount of time - the FCM to APNs link. But how would I debug it?
Here in
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
...
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
return true
}
func tokenRefreshNotification(_ notification: Notification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
// Here you get the refreshed token
// here you can connect to fcm and do subscribe to notifications
}
}
Hopefully it will solve the problem.

How to debug Notifications on iOS With Firebase

I have followed the tutorial to setup Notifications on iOS and I have checked that in the application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken token: NSData) function that a FCM token was available FIRInstanceID.instanceID().token().
From the Firebase Console I tried to send a notification (status is Completed) but no notification was received on my iOS Device.
In order to check the 'Apple side', I have uploaded y push notification certificates into another Push Notification Service Provided and it works.
So I would like to know how can I debug my application?

Resources