iT邦幫忙

0

Swift Realm 儲存 後台/app關閉 的推播資訊(求助)

各位先進端午節假期快樂
小弟在後台使用FCM來推播到ios設備,我想把推播資訊儲存下來(使用Realm)
現在只有兩種情況有辦法儲存成功
1.app執行中
2.app關閉/背景,點擊推播橫幅通知
我希望能過做到app關閉/背景也可以儲存通知

所以我用了以下的方法
1.專案中新增Notification Service Extention
2.啟用 Background fetch/Remote notifications
3.專案及Notification Service Extention加到app groups中
接下來問題就出現了,我在UNNotificationServiceExtension中使用了和AppDelegates一樣儲存推播程式碼,卻沒有效果,查閱了一些相關資訊,似乎是因為Extension無法共享realm的資料表,那我該怎麼做才能讓他們共享資料?
又小弟這種作法無法在後台儲存推播資料?煩請各位高手幫助小弟了

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"
    }
}
class RealmDao: NSObject {
    
    static let shared = RealmDao()
    private var realm: Realm!
    
    private override init() {
        
        self.realm = try! Realm()
    }
    
    func getRealmObject() -> Realm {
        return self.realm
    }
}

class NotificationService(NotificationService.swift)

import UserNotifications
import UIKit
import RealmSwift
import Realm

class NotificationService: UNNotificationServiceExtension {
   
    //
    let realm = try! Realm()
    let order: Order = Order()
    //
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
      
        let message = request.content.userInfo
        print("userInfo: \(message)")
        guard
            let aps = message[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSDictionary,
            let title = alert["body"] as? String,
            let body = 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)
        }       
        
        if let bestAttemptContent = bestAttemptContent {
            // Modify the notification content here...
            bestAttemptContent.body = "\(bestAttemptContent.body) [測試]"
            
            contentHandler(bestAttemptContent)
        }
    }
    
    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }

}

前景儲存推播通知(AppDelegates.swift)

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

   func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // 印出後台送出的推播訊息(JOSN 格式)
        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])
    }

1 個回答

0
matthewchi
iT邦新手 5 級 ‧ 2019-07-29 17:10:20

您好!我也卡在這!請問大大最後有解決了嗎?

我要發表回答

立即登入回答