AWS SNS push notification not received on iPhone 6 and above - ios

My coworker and I are building an app and implementing push notification feature utilizing AWS SNS API.
The issue here is that some devices work fine but some like iPhone 6,7,8 receive no notification regardless of the OS version (they're mostly iOS 11,12).
We've covered the basic by checking the below points:
notification turned on on all test devices
testers grant permission to receive notification at the app launch time
the p12 certificate uploaded to AWS is valid and the format is correct
The error messages we got from AWS CloudWatch Logs mostly were "bad device token" or "unregistered", but we are sure that we upload the device token as soon as we got it from APNS.
EDIT: actual code added
Register for notification (within didFinishLaunchingWithOptions)
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if let error = error {
print("\(error.localizedDescription)")
} else {
application.registerForRemoteNotifications()
}
}
Get token
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("Successfully registered for notifications!")
// upload token to our database for later use
}
Is there anything we are missing?

Related

Not receiving Push Notifications in iOS Anymore

For some reason I am not receiving push notifications on my app anymore (though users are still).
I used to receive them in production and on test flight builds, but not builds directly from Xcode. But now I am not receiving them on production nor test flight and I do not know the issue.
I created new certificates for push notifications in the developer portal and have this code in the AppDelegate. Is there any reason that push notifications would just stop working? I have notifications enabled and have tried deleting + redownloading from the App Store, but no luck
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { granted, _ in
guard granted else { return }
// Enable or disable features based on authorization
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}

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.

Why push notification directed to specific iOS device from Web API through Firebase FCM does not arrive?

I'm working with a remote web API developer, currently we're working to send push message from the server to iOS and Android device. We send our device token via OAuth API. (For iOS, device token is gotten from registering remote service with APNS service at AppDelegate launch). The weird thing is, Android can get the push notification, but iOS devices don't. But when I tried using the Firebase console -> grow -> notification -> New Message -> and target all the iOS device, all the iOS device registered to the push notification receive the push notification. Can you help me point out where the problem is? The web server is using nodeJs.
Things I have done, which I did according to this tutorial:
create new apps in Firebase project.
supply the same product bundle id to the app.
import google plist to the Xcode project.
supply development and production certificate .p12 to the app.
install Firebase/Core and Firebase/Messaging through Cocoapods.
use this code to register for remote notification (have tried both in target deployment iOS version 9.0 and 10.0, both yields the same result):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 data message (sent via FCM
Messaging.messaging().delegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
return true
}
From all this preparation, if I run the app in real iOS device, and then lock it, any message I broadcast to iOS device in the Firebase iOS app will shown in the lock screen notification. But not message from the web API that's directed toward the account logged in the app (which is directed to all the android and iOS device that logged in using that account -- it's shown on the android devices, but not on iOS devices).
I'm new to FCM. I usually use APNS. I probably don't know much about the terms to fix the server side as I don't understand nodeJs much, so if you have some suggestion about the server side, please be elaborate, so I can discuss it with the web API dev. Thanks for your help.
Turns out what I need to send to the server is not APNS token, but Firebase token, found in here:
https://firebase.google.com/docs/cloud-messaging/ios/client#monitor-token-generation

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.

Push notification not sending from my device only - Parse

I have an app currently in beta-testing that has messaging functionality. It's set up to deliver a push notification when a user receives a new message from another user. The only time push notifications work is when a user sends a message to me specifically. If I try to send a message to any other user or any users message each other that don't include me, push notifications do not work. Only messages sent to me trigger push notifications on my device.
Here are some simple screenshots from Parse showing one push that sent properly and one that did not.
This is a private message sent from another user named "Alissa" to me in which I receive the push notification properly (as you can see by "pushes sent" = 1):
Here are the details of said push:
Now, here is a private message sent from my device, the same device that received the push notification properly, back to "Alissa". As you can see, the "pushes sent" = 0, meaning my device sent the message but the recipient did not receive the push notification:
And here are the details of that push, containing virtually identical information to the working one sent to me:
Finally, here is another push not working sent between "Alissa" and another user that is not me, therefore 2 users separate from my device.
This is the pattern when I look at a list of all pushes from users in my app. They all have "pushes sent" = 0 except for when a push is sent to my device, "pushes sent = 1".
I've printed to the console in my push notification method completion handlers and they indicate that the push was sent successfully when I send a message to another user. I will also point out that my device is being used for development of this app.
Also as a side note, it did not always use to be like this. A couple weeks ago everything was working normally. I released multiple new builds and never had a problem.
Can anyone guide me in the right direction here?
Edit: Below I've included more details including code in my app and
details of my developer account and Parse backend.
Relevant code in my app
The following is code I have in my AppDelegate as recommended by Parse to include for setting up push notifications. It's worth noting that the println statements "did register user notification settings" and "did register for remote notifications with device token" are both logged properly on app launch.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// ...
let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
// ...
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
println("did register user notification settings")
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
PFInstallation.currentInstallation().setDeviceTokenFromData(deviceToken)
PFInstallation.currentInstallation().saveInBackground()
println("did register for remote notifications with device token")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println("didFailToRegisterForRemoteNotificationsWithError: ", error.localizedDescription)
}
This is code I have included when a message is sent to another user. It's also worth nothing that the println statement "success" is logged properly.
PFInstallation.query().whereKey("user", equalTo: incomingUser)
PFPush().setQuery(pushQuery)
let senderName = PFUser.currentUser()!.objectForKey("name") as! String
let data = [
"alert" : "New message from \(senderName)",
"badge" : "Increment"
]
push.setData(data)
push.sendPushInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if success {
println("success")
} else {
println(error?.localizedDescription)
}
}
Relevant details from my developer account
Here is a screenshot showing my App ID in my developer portal. It seems to show that push notifications are enabled properly (I deleted and re-added all certificates with a new provisioning profile)
Relevant details from my Parse account
Here are my push notifications settings within Parse. All this information was updated yesterday when I recreated certificates.
This might provide some level of insight although I'm not sure what. This is a screenshot of my PFInstallations table in Parse. An installation is created anytime someone logs in/opens the app. I just ran the application on my device and my record in the table is the top one. What's different from the rest is that there is a value in the "deviceToken" column only for my device. When I delete my PFInstallation record and restart the app to recreate it, there is always a value created under "deviceToken".
Relevant details from Xcode
Here is an expanded view of the code signing in my Xcode build settings. This code signing is identical in both the project and the target code signing.
Again, push notifications are working for all users messaging other users and only not working when a message is sent from my device to any other user.
Start with what makes your device unique, and it's status as a development environment device is the likely culprit.
A good place to check is your device's build and the consequent push certificate being used. If your device is in dev mode (meaning you are building and deploying to your phone via Xcode), then it will use the push certificate for Development instead of Production. (For more on this difference, see this great article by Ray Wenderlich)
The key factor here is that only your device will use this different certificate. If it's revoked/broken/not installed, only your device will have this problem.
You can also test this by deploying the app to your phone via TestFlight / HockeyApp / etc. instead of letting Xcode load it.
UPDATE:
Just pouring over the code, checking for errors. One thing already of note: your didFinishLaunchingWithOptions includes an extra PFInstallation.currentInstallation().saveInBackground() - you should remove that and only have it in the didRegisterForRemoteNotificationsWithDeviceToken method.
This is why only your device has an ID in it's PFInstallation, and is probably why your device can't reach anyone else - the push system is working, but it no no address to call out to from there; it would be a silent fail on the push, not on the parse system.
Have you tried having your users send a push to each other, or only to you and from you?

Resources