【问题标题】:Push notification is not working when app is in background (minimized) - iOS当应用程序处于后台(最小化)时,推送通知不起作用 - iOS
【发布时间】:2019-01-04 04:00:57
【问题描述】:

我是 Swift 新手,我正在创建聊天应用程序,我需要在应用程序处于前台或最小化时发送通知。

但是当应用程序最小化时我没有收到通知(它在连接 USB 时有效。

  1. 启用远程通知

  2. Xcode 设置中的后台获取

  3. 启用推送通知

  4. 生产 APns 证书

通知代码:

class AppDelegate: UIResponder, UIApplicationDelegate {

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

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

        FirebaseApp.configure()

        Messaging.messaging().delegate = self
        Messaging.messaging().shouldEstablishDirectChannel = true

        if #available(iOS 10.0, *) {

            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .sound, .badge]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        NotificationCenter.default.addObserver(self, selector: #selector(tokenRefreshNotification(_:)), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)

        return true
    }

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

        Messaging.messaging().appDidReceiveMessage(userInfo)         
    }

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

        Messaging.messaging().appDidReceiveMessage(userInfo)

        let action = userInfo["action"] as! String
        let notification = UILocalNotification()
        notification.fireDate = NSDate() as Date
        notification.alertTitle = "test"
        notification.alertBody = "test"
        notification.alertAction = "Ok"
        UIApplication.shared.applicationIconBadgeNumber =  1
        UIApplication.shared.scheduleLocalNotification(notification)

        completionHandler(UIBackgroundFetchResult.newData)
    }

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

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")

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

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo

        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        completionHandler([.alert, .sound, .badge])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        print(userInfo)

        completionHandler()
    }
    @objc func tokenRefreshNotification(_ notification: Notification) {
            guard let token = InstanceID.instanceID().token() else {
            print("No firebase token, aborting registering device")
            return
        }
        print("No firebase token, aborting registering device")           
    }
}   

extension AppDelegate : MessagingDelegate {
    // [START refresh_token]
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
        Messaging.messaging().subscribe(toTopic: "/topics/channel_18")           
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
    }        
}

FCM 负载:

 {
     "to" : "/topics/channel_18",
     "data" : {
      "action" : "NOTIFY",
      "message" : "{"text":"test" }"
     },
     "content_available" : true
    }

我尝试过使用高优先级和声音选项,但没有任何效果。

请注意,我没有按照客户的要求使用“通知”键。我在 FCM 有效负载中仅使用数据消息

当应用在后台没有 USB 连接时,请任何人帮助我通知工作。

【问题讨论】:

  • 只是要明确一点:当应用程序处于前台时它可以工作?但是当你按下主页按钮时不起作用?
  • 1. “但是当应用程序最小化时我没有收到通知(它在连接 USB 时工作。”这是什么意思?2.您是在物理设备上测试还是在使用模拟器?
  • 我正在使用物理设备
  • 屏幕锁定时通知不起作用
  • 只是为了确定,你是在杀死应用程序吗?即你双击主页按钮,然后向上滑动应用程序?你也见过here

标签: firebase push-notification apple-push-notifications swift4 ios11.3


【解决方案1】:

如果它适用于非静默通知,那么这意味着:

  • 那么有效负载设置不正确。根据对此question 提供的答案,我只需将content_available 字段的位置更改为notification(并且由于您不想要标题正文,所以不要添加标题/正文)或只是进入有效载荷本身,直到看到它工作。
  • 我还要确保在 Xcode 中设置了所有正确的功能(启用远程通知、Xcode 设置中的后台获取、启用推送通知)。如前所述,取消选中并再次重新选中所有这些。
  • 并确保为您的应用启用了后台应用刷新。这与您的通知不同。显然,请确保您的通知也已启用。:

  • 但是,如果您尝试了所有方法,但它对 11.3 不起作用,那么它可能是一个错误。还有一个open question 提到了你的同一个问题。通过点击应用程序直接运行应用程序,即从 Xcode 启动,然后使用控制台查看与静默通知相关的日志记录。如果你得到这样的东西:
default 13:11:47.178186 +0200   dasd    DuetActivitySchedulerDaemon Removing a launch request for application <private> by activity <private>   default com.apple.duetactivityscheduler

那么很可能是类似于iOS11 question 的错误。但是你必须打开一个新的雷达,因为我相信那个雷达是关闭的,因为它是固定的!

【讨论】:

  • 通知(后台应用)适用于IOS10.2,但不适用于最新的IOS版本
  • 有趣。在我的另一个answer 中,我在 iOS 11 中链接了一个类似的错误。但它已在 11.1 版本中修复。你是说你在 11.3 上测试,所以你可能只需要提交一个雷达,如果它不适用于这个版本......
  • 我的 ios 版本是 11.4.1 beta 最新的不是,但仍然是同样的问题,我已经在 IOS 版本 10.2 移动它工作过
  • 你的版本是什么? 11.4.1 测试版与否?
  • 版本为 11.4.1(15G5077a)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
  • 1970-01-01
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多