我正在使用Firebase(FCM)并尝试在Realm中保存数据。大多数应用程序都喜欢whatsaap / fb messager,即使这些应用程序已被杀死,但如果您不执行任何操作,仍可以接收通知数据。
当应用程序被杀死/关闭时,FireBase PushNotification我什么也不做(离开它)然后就无法保存数据。但是当我点击通知然后就可以保存数据了。 其他都进展顺利。
这是我的appdelegate来源
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
let realm = try! Realm()
let realmData: RealmData = RealmData()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
if let userInfo = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] {
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
print("enterbackground")
}
func applicationWillEnterForeground(_ application: UIApplication) {
print("willenterbackground")
}
func applicationDidBecomeActive(_ application: UIApplication) {
print("restart")
}
func applicationWillTerminate(_ application: UIApplication) {
print("terminated")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any])-> Void {
print("receive message")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
guard
let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String,
let title = alert["title"] as? String
else {
// handle any error here
return
}
let state = UIApplication.shared.applicationState
if state == .background {
print("I'm in the background place")
realmData.title = title
realmData.body = body
try! realm.write {
realm.add(realmData)
}
completionHandler(UIBackgroundFetchResult.newData)
}
else if state == .active {
print("I'm in the active place")
realmData.title = title
realmData.body = body
try! realm.write {
realm.add(realmData)
}
completionHandler(UIBackgroundFetchResult.newData)
}
else if state == .inactive{
print("I'm in the inactive statement")
realmData.title = title
realmData.body = body
try! realm.write {
realm.add(realmData)
}
completionHandler(UIBackgroundFetchResult.newData)
}
else{
print("I'm in the else statement")
realmData.title = title
realmData.body = body
try! realm.write {
realm.add(realmData)
}
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)")
}
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
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler([.badge, .sound, .alert])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print("userInfo: \(userInfo)")
guard
let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String,
let title = alert["title"] as? String
else {
// handle any error here
return
}
print("Title: \(title) \nBody:\(body)")
realmData.title = title
realmData.body = body
try! realm.write {
realm.add(realmData)
}
completionHandler()
}
}
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
}
这是我的json
{
"to": "device_token",
"content_available" : true,
"mutable-content" : true,
"priority" : "high",
"notification": {
"title": "test1",
"body" : "testbody1"
"badge" : "1",
"sound" : "default",
"forceStart": "1"
},
"data": {
"url": "url"
}
}