如何使用 FCM (iOS) 获取远程通知的内容?
Posted
技术标签:
【中文标题】如何使用 FCM (iOS) 获取远程通知的内容?【英文标题】:How to get the content of remote notification using FCM (iOS)? 【发布时间】:2017-01-14 18:29:54 【问题描述】:我正在使用 FCM 向使用此方法的设备发送推送通知
func push(message: String, toUser: String)
var token: String?
for person in self.users
if toUser == person.username && person.firebaseToken != nil
token = person.firebaseToken
if token != nil
var request = URLRequest(url: URL(string: "https://fcm.googleapis.com/fcm/send")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=[your FCM Server Key]", forHTTPHeaderField: "Authorization")
let json = [
"to" : token!,
"priority" : "high",
"notification" : [
"body" : message
]
] as [String : Any]
do
let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) data, response, error in
guard let data = data, error == nil else
print("Error=\(error)")
return
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
// check for http errors
print("Status Code should be 200, but is \(httpStatus.statusCode)")
print("Response = \(response)")
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
task.resume()
catch
print(error)
但设备只是获取消息而没有对其进行任何操作。 我也在尝试保存它的内容。我怎样才能做到这一点?将其保存到 Firebase 数据库是唯一的选择吗?
谢谢。
【问题讨论】:
【参考方案1】:您需要通过 AppDelegate 处理通知。您将首先在 didFinishLaunchingWithOptions 中注册通知。由于 firebase 在首次启动消息传递时没有密钥,因此您还需要注册以观察该值:
// register for remote notifications:
if #available(ios 10.0, *)
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: (_, _) in )
UNUserNotificationCenter.current().delegate = self
FIRMessaging.messaging().remoteMessageDelegate = self
else
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
NotificationCenter.default.addObserver(forName: NSNotification.Name.firInstanceIDTokenRefresh, object: nil, queue: nil, using: tokenRefreshNotification(_:))
然后你需要一个连接到 FCM 的方法:
extension AppDelegate
func connectToFCM()
FIRMessaging.messaging().connect (error) in
if error != nil
print("unable to connect to FCM \(error)")
else
print("connected to FCM")
以及获得新令牌时的处理方式:
extension AppDelegate
func tokenRefreshNotification(_ notification: Notification)
if let refreshedToken = FIRInstanceID.instanceID().token()
UserDefaults.standard.set(refreshedToken, forKey: "registrationToken")
connectToFCM()
最后,您需要实际处理通知。推送通知的实际内容在 iOS 10 及更高版本的“通知”对象中:
@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
PushService.handle(userInfo) // do whatever you need with this
而要处理其他类型的通知,您可以使用旧方法:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any])
//user tapped on notification
PushService.handle(userInfo) // do what you need with the userInfo dict here, which contains the push notification information
【讨论】:
谢谢!如果设备没有收到通知,您知道通知将保留多长时间吗?如果我发送显示“123”的通知并且另一台设备已关闭,然后我在一周后打开它,应用程序会收到推送吗?或者如果应用程序打开了,它仍然会调用这些函数来保存数据吗? 在设备上收到通知后,它会一直保留在设备上,直到应用程序再次打开。如果应用程序是后台的,它将调用 didReceieveRemoteNotification 或 ios 10 等效项(userNotificationCenter),但如果应用程序已关闭,则推送通知有效负载将包含在应用程序的“选项”中(didFinishLaunchingWithOptions)以上是关于如何使用 FCM (iOS) 获取远程通知的内容?的主要内容,如果未能解决你的问题,请参考以下文章
使用 php 向 ios 设备发送带有 fcm 令牌的远程通知
FCM 推送通知在返回应用程序时打开,而不是在 iOS 的状态栏中显示
如何在应用程序处于后台(ios)时使 FCM 通知正常工作?
如何在 ios 中单击通知时接收数据,当应用程序被杀死时,(react-native-fcm 模块在 IOS 中获取推送通知)