Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
应用程序处于后台模式或强制停止iOS 10时,不会收到推送通知_Ios_Swift_Swift3_Firebase Cloud Messaging - Fatal编程技术网

应用程序处于后台模式或强制停止iOS 10时,不会收到推送通知

应用程序处于后台模式或强制停止iOS 10时,不会收到推送通知,ios,swift,swift3,firebase-cloud-messaging,Ios,Swift,Swift3,Firebase Cloud Messaging,我已经使用Swift 3在iOS 10中实现了firebase推送 当我从firebase发送推送时,我可以接收推送消息,但仅当应用程序处于前台模式时。当应用程序处于后台模式或强制停止时,我不会收到任何消息 代码如下: import UIKit import Firebase import UserNotifications import FirebaseInstanceID import FirebaseMessaging @UIApplicationMain class AppDelega

我已经使用Swift 3在iOS 10中实现了firebase推送

当我从firebase发送推送时,我可以接收推送消息,但仅当应用程序处于前台模式时。当应用程序处于后台模式或强制停止时,我不会收到任何消息

代码如下:

import UIKit
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?


  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    if #available(iOS 10.0, *) {
      let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
      UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_,_ in })

      // For iOS 10 display notification (sent via APNS)
      UNUserNotificationCenter.current().delegate = self
      // For iOS 10 data message (sent via FCM)
      FIRMessaging.messaging().remoteMessageDelegate = self

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

    application.registerForRemoteNotifications()
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(self.tokenRefreshNotification),
                                           name: .firInstanceIDTokenRefresh,
                                           object: nil)
    FIRApp.configure()
    return true
  }

  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.
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")
  }

  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.
    connectToFcm()
  }

  func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  }

  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

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
  }

  // [START refresh_token]
  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()
  }
  // [END refresh_token]

  func connectToFcm() {
    FIRMessaging.messaging().connect { (error) in
      if (error != nil) {
        print("Unable to connect with FCM. \(error)")
      } else {
        print("Connected to FCM.")
      }
    }
  }

}


@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
    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
  }

  @available(iOS 10, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Userinfo \(response.notification.request.content.userInfo)")
    //    print("Userinfo \(response.notification.request.content.userInfo)")
  }
}

extension AppDelegate : FIRMessagingDelegate {
  // Receive data message on iOS 10 devices.
  func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print("%@", remoteMessage.appData)
  }
}

请检查您的
APNS
格式

默认格式如下所示

{
    aps =     {
        "content-available" = 1;
    };
    "gcm.message_id" = value;
    title = value;
}
把这个换成这个

{
    aps =     {
        alert =         {
            title = value;
        };

    };
    "gcm.message_id" = ;
}
在DidRegisterForRemotionTificationsWithDeviceToken方法中,添加以下代码:

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]])
  }

  FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)

  print("tokenString: \(tokenString)")
}
func应用程序(应用程序:UIApplication,didRegisterForRemotionTificationswithDeviceToken deviceToken:NSData){
让tokenChars=UnsafePointer(deviceToken.bytes)
var tokenString=“”

对于0中的i..根据您的问题,您已成功地在前台获得推送通知,但未在后台模式。为此,您勾选了功能的“后台模式中的远程通知”部分

请查看下面的屏幕截图以了解更多信息


希望它对您有用。

感谢大家的支持。以下是使用Swift 3iOS 10的最终工作代码

import UIKit
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?


  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    if #available(iOS 10.0, *) {
      let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
      UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_,_ in })

      // For iOS 10 display notification (sent via APNS)
      UNUserNotificationCenter.current().delegate = self
      // For iOS 10 data message (sent via FCM)
      FIRMessaging.messaging().remoteMessageDelegate = self

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

    application.registerForRemoteNotifications()
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(self.tokenRefreshNotification),
                                           name: .firInstanceIDTokenRefresh,
                                           object: nil)
    FIRApp.configure()
    return true
  }

  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.
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")
  }

  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.
    connectToFcm()
  }

  func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  }

  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let chars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
    var token = ""

    for i in 0..<deviceToken.count {
      token += String(format: "%02.2hhx", arguments: [chars[i]])
    }

    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)

    print("Device Token = ", token)
  }

  func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Did Fail to Register for Remote Notifications")
    print("\(error), \(error.localizedDescription)")
  }

  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

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
  }

  // [START refresh_token]
  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()
  }
  // [END refresh_token]

  func connectToFcm() {
    FIRMessaging.messaging().connect { (error) in
      if (error != nil) {
        print("Unable to connect with FCM. \(error)")
      } else {
        print("Connected to FCM.")
      }
    }
  }

}


@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
    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
  }

  @available(iOS 10, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Userinfo \(response.notification.request.content.userInfo)")
    //    print("Userinfo \(response.notification.request.content.userInfo)")
  }
}

extension AppDelegate : FIRMessagingDelegate {
  // Receive data message on iOS 10 devices.
  func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print("%@", remoteMessage.appData)
  }
}
导入UIKit
进口火基
导入用户通知
导入FirebaseInstanceID
导入FirebaseMessaging
@UIApplicationMain
类AppDelegate:UIResponder、UIApplicationLegate{
变量窗口:UIWindow?
func应用程序(application:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptions:[UIApplicationLaunchOptions:任何]?)->Bool{
//应用程序启动后自定义的覆盖点。
如果可用(iOS 10.0,*){
let authOptions:UNAuthorizationOptions=[.alert、.badge、.sound]
UnuseNotificationCenter.current().requestAuthorization(
选项:authOptions,
completionHandler:{{{,{in})
//对于iOS 10显示通知(通过APNS发送)
UnuseNotificationCenter.current().delegate=self
//对于iOS 10数据消息(通过FCM发送)
FIRMessaging.messaging().remoteMessageDelegate=self
}否则{
let设置:UIUserNotificationSettings=
UIUserNotificationSettings(类型:[.alert、.badge、.sound],类别:nil)
application.registerUserNotificationSettings(设置)
}
应用程序.注册表项更改()
NotificationCenter.default.addObserver(self,
选择器:#选择器(self.tokenRefreshNotification),
名称:.firInstanceIDTokenRefresh,
对象:无)
FIRApp.configure()
返回真值
}
func应用程序WillResignActive(application:UIApplication){
//当应用程序即将从活动状态移动到非活动状态时发送。这可能发生在某些类型的临时中断(如来电或短信)或用户退出应用程序并开始转换到后台状态时。
//使用此方法暂停正在进行的任务、禁用计时器和使图形渲染回调无效。游戏应使用此方法暂停游戏。
}
func应用程序标识符背景(u应用程序:UIApplication){
//使用此方法释放共享资源、保存用户数据、使计时器无效,并存储足够的应用程序状态信息,以便在应用程序稍后终止时将其恢复到当前状态。
//如果您的应用程序支持后台执行,则会调用此方法而不是applicationWillTerminate:当用户退出时。
FIRMessaging.messaging().disconnect()
打印(“与FCM断开连接”)
}
func应用程序将进入前台(application:UIApplication){
//作为从后台转换到活动状态的一部分调用;在这里,您可以撤消在进入后台时所做的许多更改。
}
func applicationIDBecomeActive(u应用程序:UIApplication){
//重新启动应用程序处于非活动状态时暂停(或尚未启动)的所有任务。如果应用程序以前位于后台,可以选择刷新用户界面。
connectToFcm()
}
func应用程序将终止(application:UIApplication){
//当应用程序即将终止时调用。如果合适,请保存数据。另请参阅ApplicationIdentinterBackground:。
}
func应用程序(application:UIApplication,DidRegisterForRemotionTificationswithDeviceToken deviceToken:Data){
让chars=(deviceToken作为NSData).bytes.bindMemory(to:CChar.self,capacity:deviceToken.count)
var token=“”
对于0中的i..Void){
//如果您在应用程序处于后台时收到通知消息,
//在用户点击启动应用程序的通知之前,不会触发此回调。
//TODO:处理通知的数据
//打印消息ID。
打印(“消息ID:\(userInfo[“gcm.Message\u ID”!))
//打印完整消息。
打印(“%@”,用户信息)
}
//[启动刷新\u令牌]
func tokenRefreshNotification(notification:notification){
如果让refreshedToken=FIRInstanceID.instanceID().token(){
打印(“InstanceID标记:\(刷新标记)”)
}
//连接到FCM,因为在使用令牌之前尝试连接时可能失败。
connectToFcm()
}
//[结束刷新\u令牌]
func connectToFcm(){
FIRMessaging.messaging().connect中的{(错误)
如果(错误!=nil){
打印(“无法连接FCM.\(错误)”)
}否则{
打印(“连接到FCM”)
}
}
}
}
@可用(iOS 10,*)
扩展AppDelegate:UNUserNotificationCenterDelegate{
//接收iOS 10设备的显示通知。
func userNotificationCenter(center:UNUserNotificationCenter,
将提交通知:未通知,
withCompletionHandler comple