• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - 如何在应用程序处于后台(ios)时使 FCM 通知正常工作?

[复制链接]
菜鸟教程小白 发表于 2022-12-11 17:06:55 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在将 Firebase 与我的 IOS 应用程序一起使用,并且我正在尝试设置推送通知。

目前,当我的应用程序在前台时,我能够接收推送通知,但是当我将其置于后台时,我无法接收任何消息。

在我的应用功能中,我在后台模式部分启用了推送通知和远程通知。

我目前正在使用 Postman 发送以下 POST 请求:

https://fcm.googleapis.com/fcm/send

Content-Type:application/json
Authorization:key=<my_server_key>

{   "to" : "token_id",
    "priority":"high",
    "data":{  
      "title":"mytitle",
      "body":"mybody",
      "url":"myurl"
   },
   "notification":{  
      "title":"mytitle",
      "body":"mybody",
      "content_available": true
   }
}

发送请求后,我收到状态 200 和以下响应:

{
  "multicast_id": 7920502412622407470,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
   {
      "message_id": "0:1469561276461379%345a0fe5f9fd7ecd"
    }
  ]
}

我按照这两个指南设置接收消息时发送:

https://firebase.google.com/docs/cloud-messaging/ios/client#receive_messages_through_messaging

https://firebase.google.com/docs/cloud-messaging/ios/certs

这是我的 AppDelegate 文件:

AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    override init(){
        // Configure Firebase
        FIRApp.configure()
        // Mantain data offline (persists state)
        FIRDatabase.database().persistenceEnabled = true
    }

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Register for remote notifications
        if #available(iOS 8.0, *) {
            // [START register_for_notifications]
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
            // [END register_for_notifications]
        } else {
            // Fallback
            let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
            application.registerForRemoteNotificationTypes(types)
        }

        // Add observer for InstanceID token refresh callback.
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)


        // Override point for customization after application launch
        return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
        if notificationSettings.types != .None {
            application.registerForRemoteNotifications()
        }
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        let refreshedToken = FIRInstanceID.instanceID().token()!
        print("InstanceID token:", refreshedToken)
    }

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        print("Failed to register:", error)
    }

    func application(application: UIApplication, openURL url: NSURL,
                             sourceApplication: String?,
                             annotation: AnyObject) -> Bool {

        return FBSDKApplicationDelegate.sharedInstance().application(
            application,
            openURL: url,
            sourceApplication: sourceApplication,
            annotation: annotation)
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

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

    func tokenRefreshNotification(notification: NSNotification) {
        let refreshedToken = FIRInstanceID.instanceID().token()!
        print("InstanceID token: \(refreshedToken)")

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

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

    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.
    }

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

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

}



Best Answer-推荐答案


您需要在您的 Xcode 项目配置文件中检查“远程通知”。看着 this screeenshot

虽然如果您的应用在后台,则不会传递消息。例如。如果你杀了它或者还没有启动

关于ios - 如何在应用程序处于后台(ios)时使 FCM 通知正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38598795/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap