How to store ios push notifications when the app is killed using swift
Asked Answered
L

1

1

I use my own server, use FCM to push notifications to the ios device, push notifications are successful, I also use the Realm database system to help me store the fcm push notifications, but the storage will only succeed in the following two cases. Case1: When the app is running.

Case2: The app is killed, or running in the background, when you click to push the banner notification.

But this is not my main intention. I know that when the app is killed, I can't handle the push notifications, so I want to be able to store the push notifications when the user opens the app.

Sorry, my English is not good. If there is something unclear, please let me know.

Realm class

class Order: Object {

    @objc dynamic var id = UUID().uuidString
    @objc dynamic var name = ""
    @objc dynamic var amount = ""
    @objc dynamic var createDate = Date()

    override static func primaryKey() -> String? {
        return "id"
    }

    let realm = try! Realm()
    let order: Order = Order()

AppDelegate.swift (when app runing store fcm message)

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {


        let userInfo = notification.request.content.userInfo //
        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)")

        order.name = title
        order.amount = body
        try! realm.write {
            realm.add(order)
        }
        completionHandler([.badge, .sound, .alert])
    }

click to push the banner notification AppDelegate.swift (when app killed or on backgroung click to push the banner notification)

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

        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)")

        order.name = title
        order.amount = body
        try! realm.write {
            realm.add(order)
        }
        completionHandler()
    }

Please have experienced people to help me, thank you very much.

Leary answered 6/6, 2019 at 8:11 Comment(0)
A
5

You can store notifications into your database when your app is killed.

  1. Add "Notification Service Extention" to your app.
  2. Enable Background fetch/Remote notifications Capabilities into your app.
  3. Enable "App Groups" into your app and enable the same with your "Notification Service Extention".

enter image description here

enter image description here

  1. Now you can access your database using "App Groups", and can insert notifications into your database as soon as you receive the notification.

To access database using "App Group" use,

var fileMgr : FileManager!
let databasePathURL = fileMgr!.containerURL(forSecurityApplicationGroupIdentifier: "<APP_GROUPS_ID>")

From above code once you get the path for database, you can perform your insert operation into database. It would be your normal insert operation that you are performing.

Insert code for saving data in this file and in the method highlighted in below image.

enter image description here

For accessing your files into Extention follow the below image. enter image description here

If you need any other help, Do let me know.

Armful answered 6/6, 2019 at 10:4 Comment(10)
Thank you for your answer. This is my first time using this method. Can you explain the details of Step 3, Step 4, and provide some code?For example, in step 3, I just need to turn the App and Notification Service Extention App Groups turn on?Leary
Updated Answer with images for Point3. You need to add the code for creating database with Appgroup, while creating database for the first time(maybe your database helper class). After that add the code for inserting into database in your didReceiveNotificationRequest method of service extention.Armful
Thank you very much for guiding me with pictures, let me fully understand! But I still don't know where the code is going to be added. Is it in the AppDelegate.swift where I fetch the FCM message and store it in the Realm database?Leary
@Leary Updated my answer. Please check.Armful
Thank you for your explanation, I am using the Realm database, but I can't import RealmSwift and Firebase in the NotificationService.And I don't understand. There is no information about FCM coming in here. How do I store the information?Leary
If you want to add your access files into your extention. Select the file and under Show the file inspector(Right side of Xcode), under Target Membership, select the extention. Now you will be able to access the files in extention.Armful
Updated my answer for better understanding.Armful
Thank you again for your explanation! Forgive my dullness. I still have a few questions. 1. I am trying to add firebase, Realm framework to Targe Mebership , but I use pods to install, so I can't find which side to join. 2. I don't know how to do this in NotificationService.swift, print ("push notification"), for example, I am in AppDelegats.swift, I use the code in my problem description, I can output my push notification,What code should I use to achieve this in NotificationService.swift?Leary
Let us continue this discussion in chat.Armful
I added some questions in chat.Leary

© 2022 - 2024 — McMap. All rights reserved.