如何使用FCM(iOS)获取远程通知的内容?
我使用FCM向使用此方法的设备发送推送通知如何使用FCM(iOS)获取远程通知的内容?,ios,swift,firebase,push-notification,firebase-cloud-messaging,Ios,Swift,Firebase,Push Notification,Firebase Cloud Messaging,我使用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 }
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数据库的唯一选项
谢谢。您需要通过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”,而另一个设备关闭了,然后我在一周后打开它,应用程序会得到推送吗?或者,如果应用程序已打开,它是否仍将调用这些功能来保存数据?在设备上收到通知后,它将保留在设备上,直到应用程序再次打开。如果应用程序是后台的,它将调用DidReceiveRemotonification或ios 10等效程序(userNotificationCenter),但如果应用程序已关闭,则推送通知负载将包含在应用程序的“选项”中(didFinishLaunchingWithOptions)