2016-09-01 27 views
4

私は通知サービスとしてFCMを使用する必要があるSwiftでアプリケーションを開発しています。私のアプリでは、FCMはフォアグラウンドでバックグラウンドではないときにのみ動作します。スウィズル私のペイロードにnotificationにも iOSのFCM通知がバックグラウンドで動作しない

Iをdataを変更

  • highpriority設定
  • 方法を無効にし、を可能

    • Iはすでになどのいくつかの方法を試しエラーが発生しました:

      Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)" 
      

      ただし、通知は問題なくフォアグラウンドで動作します。以下は私のAppDelegateです:

      @UIApplicationMain 
      class AppDelegate: UIResponder, UIApplicationDelegate { 
      
          var window: UIWindow? 
      
          func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
      
           FIRApp.configure() 
      
           // Add observer for InstanceID token refresh callback. 
           NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), 
                       name: kFIRInstanceIDTokenRefreshNotification, object: nil) 
      
           return true 
          } 
      
          func registerForPushNotifications(application: UIApplication) { 
           let notificationSettings = UIUserNotificationSettings(
            forTypes: [.Badge, .Sound, .Alert], categories: nil) 
           application.registerUserNotificationSettings(notificationSettings) 
          } 
      
          func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { 
           if notificationSettings.types != .None { 
            application.registerForRemoteNotifications() 
           } 
          } 
      
          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]]) 
           } 
      
           //Tricky line 
           FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown) 
           print("Device Token:", tokenString) 
          } 
      
          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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. 
          } 
      
          // [START receive_message] 
          func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], 
              fetchCompletionHandler completionHandler: (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 
      
           let alertController = UIAlertController(title: "Notification", message: "A standard alert", preferredStyle: .Alert) 
      
           let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in 
      
           } 
           alertController.addAction(OKAction) 
      
           self.window?.rootViewController?.presentViewController(alertController, animated: true, completion:nil) 
      
           // Print message ID. 
      //  print("Message ID: \(userInfo["gcm.message_id"]!)") 
      
           // Print full message. 
           print("%@", userInfo) 
          } 
          // [END receive_message] 
      
          // [START refresh_token] 
          func tokenRefreshNotification(notification: NSNotification) { 
           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() 
          } 
          // [END refresh_token] 
      
          // [START connect_to_fcm] 
          func connectToFcm() { 
           FIRMessaging.messaging().connectWithCompletion { (error) in 
            if (error != nil) { 
             print("Unable to connect with FCM. \(error)") 
            } else { 
             print("Connected to FCM.") 
            } 
           } 
          } 
          // [END connect_to_fcm] 
      
          func applicationDidBecomeActive(application: UIApplication) { 
           connectToFcm() 
          } 
      
          // [START disconnect_from_fcm] 
          func applicationDidEnterBackground(application: UIApplication) { 
           FIRMessaging.messaging().disconnect() 
           print("Disconnected from FCM.") 
          } 
          // [END disconnect_from_fcm] 
      

      そして、私のサーバーでは、私は、通知をプッシュするために、このようなものを使用します。

      method: 'POST', 
            uri: 'https://fcm.googleapis.com/fcm/send', 
            headers: { 
             'Content-Type': 'application/json', 
             'Authorization':'key= **THE KEY**' 
            }, 
            body: JSON.stringify({ 
             "to" : " **USER INSTANCEID TOKEN** ", 
             "priority":"high", 
             "data" : { 
              "title": "FCM TITLE", 
              "body" : "FROM FCM", 
              "badge": "0", 
              "sound": "default" 
             } 
            }) 
      

      私はどこにでも探してみましたが、いずれかの解決策を見つけることができませんとすることはできませんFCMのドキュメントでこの問題について何かを見つけたようです。

  • +0

    あなたのペイロードに、データの代わりに通知キーを持つように変更すると、バックグラウンドでも動作するようになります。 – Shubhank

    +0

    @Shubhank私はすでに 'data'を' notification'に変更し、何も私のためには役に立たないと忘れました – Dirus

    +0

    アプリがバックグラウンドにあるときやアプリが死んだときに動作しないという意味ですか? – Shubhank

    答えて

    0

    は、私は、iOS \スウィフトではかなり新しいです...しかし、私は多分、このコードだと思う:firebaseクラウドメッセージングのうち

    // [START disconnect_from_fcm] 
        func applicationDidEnterBackground(application: UIApplication) { 
         FIRMessaging.messaging().disconnect() 
         print("Disconnected from FCM.") 
        } 
    // [END disconnect_from_fcm] 
    

    ログあなたは毎回アプリがバックグラウンドに行く...とあなたが通知を受け取っていない理由です。

    この方法をコメントアウトして機能するかどうか確認してください。

    LMK、ありがとう。

    0

    content_avaliabletrueの値を@ALとしてみてください。また、notificationオブジェクトを追加してください。両方のパラメータ(データと通知)で通知を送信することができます

    これは私のために働いています。

    { 
        "to" : " **USER INSTANCEID TOKEN** ", 
        "priority":"high", 
        "content_avaliable":true, 
        "data" : { 
         "title": "FCM TITLE", 
         "body" : "FROM FCM", 
         "badge": "0", 
         "sound": "default" 
        }, 
        "notification" : { 
         "title": "FCM TITLE", 
         "body" : "FROM FCM" 
        } 
    } 
    

    UPDATE: は動作が続行されたiPhoneに、私のiPadでのみ動作しています。

    関連する問題