2017-10-16 6 views
1

Nous implémentons des notifications à distance côté serveur pour un périphérique à l'autre dans IOS 11. Pour cette première nous avons créé l'application IOS sur Firebase, ainsi que des détails de messagerie cloud configurés. Tout est fait là et ensuite. Maintenant, à partir de là, la clé du serveur hérité est utilisée sur notre propre serveur, où nous avons écrit des scripts pour envoyer des notifications à distance à différents périphériques en fonction de leur jeton Firebase.Impossible de recevoir des notifications à distance du serveur dans IOS 11, swift 4?

La génération et l'élimination des notifications sont réussies dans les deux cas, que ce soit par Postman ou via un périphérique IOS. Nous avons essayé notre serveur localement et sur le cloud. Lorsque nous envoyons des messages normaux à partir de la console Firebase, cela fonctionne également très bien et nous avons reçu des notifications à distance à partir de là.

Chaque fois que nous envoyions des notifications via le serveur à Firebase, puis à l'appareil à l'aide d'APN, nous ne pouvions pas recevoir cette notification à distance.

Notre délégué App ressemble à ceci.

class AppDelegate: UIResponder, UIApplicationDelegate { 

var window: UIWindow? 
let gcmMessageIDKey = "gcm.message_id" 

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
    // Override point for customization after application launch. 
    print("Application did finish launching") 
    FirebaseApp.configure() 


    // [END set_messaging_delegate] 
    // Register for remote notifications. This shows a permission dialog on first run, to 
    // show the dialog at a more appropriate time move this registration accordingly. 
    // [START register_for_notifications] 
    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 }) 

     // [START set_messaging_delegate] 
     Messaging.messaging().delegate = self 

    } else { 
     let settings: UIUserNotificationSettings = 
      UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) 
     application.registerUserNotificationSettings(settings) 
    } 

    application.registerForRemoteNotifications() 

    // [END register_for_notifications] 


    return true 
} 

// Remote Notification 
// [START receive_message] 
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { 
    // 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 
    // With swizzling disabled you must let Messaging know about the message, for Analytics 
    // Messaging.messaging().appDidReceiveMessage(userInfo) 
    // Print message ID. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 
} 



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


    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { 
    // 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 
    // With swizzling disabled you must let Messaging know about the message, for Analytics 
    // Messaging.messaging().appDidReceiveMessage(userInfo) 
    // Print message ID. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 
    print("Received Remote Message: 4\nCheck Out:\n") 
    print("Main Remote Message: 4\nCheck Out:\n") 

    completionHandler(UIBackgroundFetchResult.newData) 
} 



// [END receive_message] 
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { 
    print("Unable to register for remote notifications: \(error.localizedDescription)") 
} 

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled. 
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to 
// the FCM registration token. 
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 
    print("APNs token retrieved: \(deviceToken)") 
    Messaging.messaging().apnsToken = deviceToken 

    print("Token is here \(String(describing: Messaging.messaging().fcmToken))") 
    print("Token is here \(String(describing: Messaging.messaging().apnsToken))") 



    if UserDefaults.standard.object(forKey: "FCM_Token") == nil 
    { 
     UserDefaults.standard.set(Messaging.messaging().fcmToken, forKey: "FCM_Token") 
    } 
    else 
    { 
     let fcmSavedToken = UserDefaults.standard.value(forKey: "FCM_Token") as! String 
     if fcmSavedToken == Messaging.messaging().fcmToken 
     { 

     } 
     else 
     { 
      UserDefaults.standard.set(Messaging.messaging().fcmToken, forKey: "FCM_Token") 
     } 


    } 



    // With swizzling disabled you must set the APNs token here. 
    // Messaging.messaging().apnsToken = deviceToken 
    } 

// End Remote Notification 


func applicationWillResignActive(_ application: UIApplication) { 
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 
} 

func applicationDidEnterBackground(_ application: UIApplication) { 
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
} 

func applicationWillEnterForeground(_ application: UIApplication) { 
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 
} 

func applicationDidBecomeActive(_ application: UIApplication) { 
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
} 

func applicationWillTerminate(_ application: UIApplication) { 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
    // Saves changes in the application's managed object context before the application terminates. 
    self.saveContext() 
} 

// MARK: - Core Data stack 

lazy var persistentContainer: NSPersistentContainer = { 
    /* 
    The persistent container for the application. This implementation 
    creates and returns a container, having loaded the store for the 
    application to it. This property is optional since there are legitimate 
    error conditions that could cause the creation of the store to fail. 
    */ 
    let container = NSPersistentContainer(name: "Git_Tutorial") 
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in 
     if let error = error as NSError? { 
      // Replace this implementation with code to handle the error appropriately. 
      // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 

      /* 
      Typical reasons for an error here include: 
      * The parent directory does not exist, cannot be created, or disallows writing. 
      * The persistent store is not accessible, due to permissions or data protection when the device is locked. 
      * The device is out of space. 
      * The store could not be migrated to the current model version. 
      Check the error message to determine what the actual problem was. 
      */ 
      fatalError("Unresolved error \(error), \(error.userInfo)") 
     } 
    }) 
    return container 
}() 

// MARK: - Core Data Saving support 

func saveContext() { 
    let context = persistentContainer.viewContext 
    if context.hasChanges { 
     do { 
      try context.save() 
     } catch { 
      // Replace this implementation with code to handle the error appropriately. 
      // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
      let nserror = error as NSError 
      fatalError("Unresolved error \(nserror), \(nserror.userInfo)") 
     } 
    } 
} 

    } 

    // Messaging 
    // Firebase 
    // Workout 
    // [START ios_10_message_handling] 
    @available(iOS 10, *) 
    extension AppDelegate : UNUserNotificationCenterDelegate { 

// Receive displayed notifications for iOS 10 devices. 
func userNotificationCenter(_ center: UNUserNotificationCenter, 
          willPresent notification: UNNotification, 
          withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
    let userInfo = notification.request.content.userInfo 

    // With swizzling disabled you must let Messaging know about the message, for Analytics 
    // Messaging.messaging().appDidReceiveMessage(userInfo) 
    // Print message ID. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 

    // Change this to your preferred presentation option 
    completionHandler([.alert, .badge, .sound]) 
} 

func userNotificationCenter(_ center: UNUserNotificationCenter, 
          didReceive response: UNNotificationResponse, 
          withCompletionHandler completionHandler: @escaping() -> Void) { 
    let userInfo = response.notification.request.content.userInfo 
    // Print message ID. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 

    completionHandler() 
} 


    } 
    // [END ios_10_message_handling] 

extension AppDelegate : MessagingDelegate { 
// [START refresh_token] 
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) { 
    print("Firebase registration token: \(fcmToken)") 
    print("Received Remote Message: 1\nCheck Out:\n") 

} 
// [END refresh_token] 
// [START ios_10_data_message] 
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground. 
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true. 
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { 
    print("Received data message: \(remoteMessage.appData)") 
    print("Received Remote Message: 2\nCheck Out:\n") 
} 




// Receive data message on iOS 10 devices while app is in the foreground. 
func application(received remoteMessage: MessagingRemoteMessage) { 
    print("Received Remote Message: 3\nCheck In:\n") 
    debugPrint(remoteMessage.appData) 
    print("Received Remote Message: 3\nCheck Out:\n") 

} 
    // [END ios_10_data_message] 
} 

Répondre

1

// MARK: // délégué UNUserNotificationCenter> = iOS 10

@available(iOS 10.0, *) 
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
    print("User Info = ",notification.request.content.userInfo) 
    completionHandler([.alert, .badge, .sound]) 
} 

@available(iOS 10.0, *) 
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 
    print("User Info = ",response.notification.request.content.userInfo) 
    completionHandler() 
} 

// MARK: Class Methods 
func registerForRemoteNotification() { 
    if #available(iOS 10.0, *) { 
     let center = UNUserNotificationCenter.current() 
     center.delegate = self 
     center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in 
      if error == nil{ 
       UIApplication.shared.registerForRemoteNotifications() 
      } 
     } 
    } 
    else { 
     UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil)) 
     UIApplication.shared.registerForRemoteNotifications() 
    } 
}