2016-09-01 74 views
4

不工作我開發斯威夫特一個應用程序,必須使用FCM的通知服務。在我的應用程序中,FCM只能在前景而不在後臺運行。的iOS FCM通知在後臺

我已經嘗試過多種方法,如:

  • 禁用和啓用混寫方法
  • 設置priorityhigh
  • 在我的有效載荷改變datanotification

我也出現錯誤:

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我忘了提及,我已經改變'數據'爲'通知'反之亦然,沒有什麼適合我 – Dirus

+0

你意味着當應用程序在後臺或應用程序處於死亡狀態時它不起作用? – Shubhank

回答

0

我在的iOS \雨燕相當新的...但我認爲,也許這代碼:

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

註銷您火力雲消息的每次應用程序轉到後臺...和這就是爲什麼你沒有收到通知。

你可以嘗試註釋掉這個方法,看看是否可行?

LMK,謝謝。

0

嘗試用true值@AL添加content_avaliable。說並添加一個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: 只工作在我的iPad,iPhone手機中的行爲仍在繼續。