[![enter image description here][1]][1]I've mentioned all the fields but still I'm not getting the push notification.
This is my code:
Firstly in didFinishLaunchingWithOptions I call this:
self.push = Sinch.managedPushWithAPSEnvironment(.Production)
self.push?.delegate = self
self.push?.setDesiredPushTypeAutomatically()
client = Sinch.clientWithApplicationKey("xxxxxx", applicationSecret: "xxxxxxx", environmentHost: "sandbox.sinch.com", userId: userID)
client?.delegate = self
client?.setSupportMessaging(true)
client?.setSupportPushNotifications(true)
client?.enableManagedPushNotifications()
client?.start()
client?.startListeningOnActiveConnection()
self.push?.registerUserNotificationSettings()
func managedPush(managedPush: SINManagedPush!, didReceiveIncomingPushWithPayload payload: [NSObject : AnyObject]!, forType pushType: String!) {
self.client?.relayRemotePushNotification(payload)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.length {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
self.push?.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
self.push?.application(application, didReceiveRemoteNotification: userInfo)
}
I've also uploaded the push certificate in my sinch dashboard.
May I know what am I missing in this code that might be the reason I'm not getting push.
EDITED:
Here is the image of the uploaded push distribution certificate on Sinch Dashboard.
http://i.stack.imgur.com/d6PVb.png
You should not have client?.setSupportPushNotifications(true) thats for when you want to handle the push your self
Related
I am using Sinch with Swift (with bridging header) for instant messaging and I don't receive any push notification when a message is received.
I have a Development Certificate in the Sinch Dashboard.
Background modes are disabled.
Push notification work with other way (Pusher)
But when I send a sinch instant message the App Delegate's "didReceiveRemoteNotification" function never gets called.
var sinClient:SINClient?
var push:SINManagedPush?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Sinch Push Notification
sinClient = Sinch.client(withApplicationKey: "-----", applicationSecret: "------", environmentHost: "sandbox.sinch.com", userId: "----")
sinClient?.setSupportMessaging(true)
sinClient?.enableManagedPushNotifications()
sinClient?.delegate = self
sinClient?.messageClient().delegate = self
sinClient?.start()
sinClient?.startListeningOnActiveConnection()
self.push = Sinch.managedPush(with: SINAPSEnvironment.development)
self.push?.delegate = self
self.push?.setDesiredPushTypeAutomatically()
self.push?.registerUserNotificationSettings()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Device Token: \(token)")
self.push?.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
self.push?.application(application, didReceiveRemoteNotification: userInfo)
}
func managedPush(_ managedPush: SINManagedPush!, didReceiveIncomingPushWithPayload payload: [AnyHashable : Any]!, forType pushType: String!) {
sinClient?.relayRemotePushNotification(payload)
}
Instant Message are received only when I open the app.
Finally I found that the problem was that I used the simulator to send the message
I am currently developing and iOS app using Swift, which I am new to, and the code generated from AWS Mobile Hub, with AWS SNS to register devices and send notifications.
On my class AWSMobileClient I have the following code:
func didFinishLaunching(_ application: UIApplication, withOptions launchOptions: [AnyHashable: Any]?) -> Bool {
print("didFinishLaunching:")
// Register the sign in provider instances with their unique identifier
AWSSignInProviderFactory.sharedInstance().register(signInProvider: AWSFacebookSignInProvider.sharedInstance(), forKey: AWSFacebookSignInProviderKey)
var didFinishLaunching: Bool = AWSIdentityManager.default().interceptApplication(application, didFinishLaunchingWithOptions: launchOptions)
didFinishLaunching = didFinishLaunching && AWSPushManager(forKey: ServiceKey).interceptApplication(application, didFinishLaunchingWithOptions: launchOptions)
if (!isInitialized) {
AWSIdentityManager.default().resumeSession(completionHandler: { (result: Any?, error: Error?) in
print("Result: \(result) \n Error:\(error)")
}) // If you get an EXC_BAD_ACCESS here in iOS Simulator, then do Simulator -> "Reset Content and Settings..."
// This will clear bad auth tokens stored by other apps with the same bundle ID.
isInitialized = true
}
return didFinishLaunching
}
Which is called normally.
On my AppDelegate, I have the following:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
AWSMobileClient.sharedInstance.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
NotificationCenter.default.post(name: Notification.Name(rawValue: AWSMobileClient.remoteNotificationKey), object: deviceToken)
print("###--- DID REGISTER FOR REMOTE NOTIFICATION ---###")
}
Which is also called.
However, when I try sending a notification using AWS SNS, my function:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("###--- DID RECEIVE REMOTE NOTIFICATION ---###")
AWSMobileClient.sharedInstance.application(application, didReceiveRemoteNotification: userInfo , fetchCompletionHandler: completionHandler)
// This is where you intercept push notifications.
if (application.applicationState == .active) {
UIAlertView.init(title: "Notification Received", message: userInfo.description, delegate: nil, cancelButtonTitle: "OK").show()
}
}
Is never called.
Looking for a solution I read that since iOS 10 there are some chances that need to be made to deal with push notification, but I'm not sure about the correct ways.
How should I implement the code to receive the notifications?
My push notifications sent from the Firebase console does not appear.. Yesterday, they appeared when i deleted my app, and freshly installed again - but only 1 time, and then they stopped appearing again. Today they dont appear at all..
I've tried to renew my APNs certificate, to create a new app on Firebase, to run the examplecode, check for correct bundle identifiers, check settings in xcode and now im lost for ideas..
I am able to receive push notifications from an APNs-tester, so I'm quite sure my certificate is good! It must be a Firebase problem somehow..
Here's my appDelegate:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().statusBarStyle = .Default
// Parse
User.initialize()
PFCategory.initialize()
Follow.initialize()
Activity.initialize()
PostElement.initialize()
PFComment.initialize()
Socials.initialize()
Notification.initialize()
let configuration = ParseClientConfiguration {
$0.applicationId = "Agpq2y3O2Gxxxxxx"
$0.clientKey = "k2bM8XTYf354fxAxxxxxxxxxx"
$0.server = "https://parseapi.back4app.com/"
$0.localDatastoreEnabled = false
}
Parse.initializeWithConfiguration(configuration)
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
// Firebase configuration
FIRApp.configure()
// Facebook
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
// Add observer for InstanceID token refresh callback.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)
//Register for remote notifications
let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
let pushNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
application.registerUserNotificationSettings(pushNotificationSettings)
application.registerForRemoteNotifications()
return true
}
// When app registered for remote notification
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print("** DEVICE TOKEN = \(deviceToken) **")
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
print("** APNS Token set!! **")
}
// When app failed to register for remote notification
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
// Print the error, if failing to register for push notifications
print("AppDelegate, failed with registering for remote notifications: \(error)")
}
// If no token, or token has changed, this method is called to refresh it!
func tokenRefreshNotification(notification: Notification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connectWithCompletion { (error) in
if error != nil {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
print("didRegisterUserNotificationSettings")
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject: AnyObject]) {
// Let FCM know about the message for analytics etc.
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print(userInfo)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// Let FCM know about the message for analytics etc.
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print(userInfo)
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return PDKClient.sharedInstance().handleCallbackURL(url) || FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
print("------APP IN BACKGROUND!!!!!------")
// Setting the user to offline in Parse - be aware of bad connection, this may fuck it up
api.setOnlineStatus("offline")
// Setting the batchnumber to 0 and disconnecting from FCM
application.applicationIconBadgeNumber = 0;
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
print("------APP DID BECOME ACTIVE!!!!!------")
firebase = FirebaseManager()
connectToFcm()
FBSDKAppEvents.activateApp()
}
func applicationWillTerminate(application: UIApplication) {
}
}
I cant see whats missing - have anyone experienced the same problem, or know about a possible solution? :)
Best regards!
I have problems getting my app to receive notifications while in background or shutdown mode. I have followed Firebase guide on how to implement firebase messaging in my app. Previously I have used GCM (google cloud messaging) and it all worked well, but since upgrading to Firebase I can't get it to work. As soon as I start my app, all the notifications that I sent (through firebase console notifications) while in background or shutdown are delivered.
I have:
Created project on Firebase console
Added my app to the firebase project with the correct bundle id
Created an APNS Development certificate
Uploaded the certificate to my app on Firebase console
Worth mentioning is that I have disabled swizzling by setting FirebaseAppDelegateProxyEnabled to NO in my Info.plist file.
Relevant code:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let types: UIUserNotificationType = [UIUserNotificationType.Badge, UIUserNotificationType.Alert, UIUserNotificationType.Sound]
let settings: UIUserNotificationSettings = UIUserNotificationSettings( forTypes: types, categories: nil )
application.registerUserNotificationSettings( settings )
application.registerForRemoteNotifications()
FIRApp.configure()
}
func connectToFcm() {
FIRMessaging.messaging().connectWithCompletion { (error) in
if (error != nil) {
print("Unable to connect with FCM")
} else {
print("Connected to FCM.")
self.refreshToken()
}
}
}
func refreshToken(){
if let refreshedToken = FIRInstanceID.instanceID().token() {
gcmToken = refreshedToken
userDefaults.setValue(gcmToken, forKey: CONSTANTS.GCM_TOKEN)
if(userDefaults.boolForKey("UserLoggedIn")){
pushGcmToken() //push the token to server
}
}
}
func onTokenRefresh() {
refreshToken()
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
NSLog("didReceiveRemoteNotification \(userInfo)")
FIRMessaging.messaging().appDidReceiveMessage(userInfo)
handleRemoteNotification(userInfo)
}
func handleRemoteNotification(userInfo: [NSObject : AnyObject]){
if let notification = userInfo["notification"] as? [NSObject : AnyObject]{
let bodyNot = notification["body"] as! String
var titleNot = "Ă„ndring"
var category = "UNIFIED_OTHER_CATEGORY"
if(notification["title"] != nil){
titleNot = (notification["title"] as! String == "Call" ? "Inkomande samtal" : notification["title"]) as! String
category = "UNIFIED_CALL_CATEGORY"
}
let notis = UILocalNotification()
notis.alertTitle = titleNot
notis.alertBody = bodyNot
notis.soundName = UILocalNotificationDefaultSoundName // play default sound
notis.userInfo = ["UUID": "122" ] // assign a unique identifier to the notification so that we can retrieve it later
notis.category = category
notis.fireDate = NSDate()
UIApplication.sharedApplication().scheduleLocalNotification(notis)
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
NSLog("didRegisterForRemoteNotificationsWithDeviceToken \(deviceToken)")
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
}
I have even tried with swizzling on. Same thing happening. I would very much appreciate any help or hint into the right direction.
I configured below things and its work fine for my application,
In info.plist set below two keys
<key>FIRMessagingAutoRegisterEnabledflag</key>
<true/>
<key>FirebaseAppDelegateProxyEnabled</key>
<false/>
In appdelegate set below code for test notification development mode
[[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
Download GoogleService-Info.plist from firebase console and put it on your application
You have to add "content-available" : true in the JSON payload. Otherwise you won't get push notification in the background mode.
"notification" : {
"content-available" : true,
"body" : "this is body",
"title" : "this is title"
}
For some reason my didReceiveRemoteNotification is never called. I have done the following:
checklist of APNS:
Create AppId allowed with Push Notification
Create SSL certificate with valid certificate and app id
Create Provisioning profile with same certificate and make sure to add device
With Code:
Register app for push notification
Handle didRegisterForRemoteNotificationsWithDeviceToken method
Set targets> Capability> background modes> Remote Notification
Handle didReceiveRemoteNotification
Yet my function does not seem to get called. My code looks like this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if (application.respondsToSelector("isRegisteredForRemoteNotifications"))
{
// iOS 8 Notifications
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: (.Badge | .Sound | .Alert), categories: nil));
application.registerForRemoteNotifications()
}
else
{
// iOS < 8 Notifications
application.registerForRemoteNotificationTypes(.Badge | .Sound | .Alert)
}
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for var i = 0; i < deviceToken.length; i++ {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
apnsID = tokenString
println("******apnsID is \(apnsID)")
dToken = deviceToken
println("******dToken is \(dToken)")
NSUserDefaults.standardUserDefaults().setObject(deviceToken, forKey: "deviceToken")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println("***********didFailToRegisterForRemoteNotificationsWithError")
println(error)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
println("Getting notification")
var message: NSString = ""
var alert: AnyObject? = userInfo["aps"]
println(userInfo["aps"])
if((alert) != nil){
var alert = UIAlertView()
alert.title = "Title"
alert.message = "Message"
alert.addButtonWithTitle("OK")
alert.show()
}
}
add content_available:true in your request . for iOS payload data.You will get notification in didReceiveRemoteNotification. Now handle it.
As I found out having the same problem myself, in order for didReceiveRemoteNotificationto be called, the incoming notification music carry an "available_content" : true parameter with the notification payload. So in case of you sending the notification in a dictionary form , as was my case in device to device pushes, you just have to add it in the dictionary as you would specify other parameters as you would for sound or badge, also needed if you're using some sort of push service as Postman
Three steps:
Add logic here to handle incoming notification:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// Add your logic here
completionHandler(.newData)
}
Add Background mode to capabilities in target, and ensure to check 'Remote notifications'
While sending a push notification, add "content_available" : true
This worked for me in iOS 14/Xcode 12.3.