0

I've used apple push notification service in my app and I received certificates and it works well But now my problem is that when I use Firebase rest API for sending message as notification I won’t receive any notification in my iPhone until I run the app But when I use Firebase it will be working, well here is my codes:

import UIKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications

 @UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    NotificationCenter.default.addObserver(self, selector: #selector(self.refreshToken(notification:)), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
    Messaging.messaging().isAutoInitEnabled = true

    FirebaseApp.configure()

    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert , .badge , .sound]) { (success, error) in
        }
    } else {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
        // Fallback on earlier versions
    }

    application.registerForRemoteNotifications()

    return true
}


func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    #if PROD_BUILD
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .prod)
    #else
        InstanceID.instanceID().setAPNSToken(deviceToken, type: .sandbox)
    #endif


        Messaging.messaging().subscribe(toTopic: "global")
}


func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

        Messaging.messaging().subscribe(toTopic: "global")

    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {


    Messaging.messaging().appDidReceiveMessage(userInfo)

    if Messaging.messaging().fcmToken != nil {
        Messaging.messaging().subscribe(toTopic: "global")
    }

    // Print full message.
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}

func applicationDidEnterBackground(_ application: UIApplication) {

    Messaging.messaging().shouldEstablishDirectChannel = false
}

func applicationDidBecomeActive(_ application: UIApplication) {
    FBHandler()
}


@objc func refreshToken(notification : NSNotification) {

    let refreshToken = InstanceID.instanceID().token()!
    print("***\(refreshToken)")
    FBHandler()
}

func FBHandler() {

    Messaging.messaging().shouldEstablishDirectChannel = true
}
}
ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
Saeed Rahmatolahi
  • 1,317
  • 2
  • 27
  • 60

1 Answers1

0

For APNS to work in background you need to enable background modes in capabilities section and tick remote notification.

enter image description here

Once you done add/check this delegate method in AppDelegate class

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    print("APNS USER INFO: \(userInfo)")
}

This method fires when app is in background and APNS comes.

More Info: How to handle push notification in background in ios 10?

UPDATE:

Add this one also and let see if it works

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        print("APNS: \(response.notification.request.content.userInfo)")
 }
Abhishek Thapliyal
  • 3,497
  • 6
  • 30
  • 69
  • this doesn't worked again as you see in my codes here the topic should be "global" but in your codes here I don't see that again it's working but not outside the app the app will receive notification when I run the app – Saeed Rahmatolahi Apr 23 '18 at 04:30
  • I can't test this because my target iOS is 9.3.5 and when I add this code it will show me to use if iOS 10.0 is available can you edit that for iOS 9.0 too please ? – Saeed Rahmatolahi Apr 23 '18 at 05:59
  • ok But after using func userNotificationCenter(_ center: this method will require iOS 10 not 9.3.5 – Saeed Rahmatolahi Apr 23 '18 at 06:14
  • But in ur code you have added version support. Also Can you test app in iOS 10? – Abhishek Thapliyal Apr 23 '18 at 06:19
  • no because when you want to get certificate for push notification you need to submit your iPhone for test so I used my iPhone 4s that iOS is 9.3.5 or I am wrong? if I can test notifications in other iPhones please tell me – Saeed Rahmatolahi Apr 23 '18 at 07:19