ios - 如何从 NotificationServiceExtension 将远程通知数据保存到核心数据(数据库)中

标签 ios swift core-data notifications serviceextension

我已经在我的目标应用程序中实现了 NotificationServiceExtension,它工作正常。

  • 创建 AppgroupID

     lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    
         var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
         let options = [
             NSMigratePersistentStoresAutomaticallyOption: true,
             NSInferMappingModelAutomaticallyOption: true
             ]
    
         let oldStoreUrl = self.applicationDocumentsDirectory.appendingPathComponent("Model.sqlite")
         let directory: NSURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppGroupID)! as NSURL
         let newStoreUrl = directory.appendingPathComponent("Model.sqlite")!
    
         var targetUrl : URL? = nil
         var needMigrate = false
         var needDeleteOld = false
    
    
         if FileManager.default.fileExists(atPath: oldStoreUrl.path){
            needMigrate = true
            targetUrl = oldStoreUrl
         }
         if FileManager.default.fileExists(atPath: newStoreUrl.path){
            needMigrate = false
            targetUrl = newStoreUrl
    
            if FileManager.default.fileExists(atPath: oldStoreUrl.path){
                needDeleteOld = true
            }
         }
         if targetUrl == nil {
            targetUrl = newStoreUrl
         }
    
         if needMigrate {
            do {
                try coordinator?.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: targetUrl!, options: options) 
                if let store = coordinator?.persistentStore(for: targetUrl!) {
                    do {
                        try coordinator?.migratePersistentStore(store, to: newStoreUrl, options: options, withType: NSSQLiteStoreType)
    
                    } catch let error {
                        print("migrate failed with error : \(error)")
                    }
                }
            } catch let error {
                //CrashlyticsHelper.reportCrash(err: error as NSError, strMethodName: "migrateStore")
                print(error)
            }
        }
    
        if needDeleteOld {
            self.deleteDocumentAtUrl(url: oldStoreUrl)
            self.deleteDocumentAtUrl(url: self.applicationDocumentsDirectory.appendingPathComponent("Model.sqlite-shm"))
            self.deleteDocumentAtUrl(url: self.applicationDocumentsDirectory.appendingPathComponent("Model.sqlite-wal"))
        }
    
        do {
            try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: targetUrl, options: options)
        } catch var error as NSError {
            coordinator = nil
            NSLog("Unresolved error \(error), \(error.userInfo)")
            abort()
        } catch {
            fatalError()
        }
        return coordinator
    
    }() 
    
      **EDIT:**
    
    lazy var applicationDocumentsDirectory: URL = {
    
    let urls = Foundation.FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return urls[urls.count-1]}()
    
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    
     self.contentHandler = contentHandler
     bestAttemptContent = (request.content.mutableCopy() as? 
     UNMutableNotificationContent)
    
    if let bestAttemptContent = bestAttemptContent {
        // Modify the notification content here...
        print("Mutable Data %@",bestAttemptContent)
        bestAttemptContent.title = "\(bestAttemptContent.title)"
        //bestAttemptContent.title = "Notification"
    
         let apnsDic = bestAttemptContent.userInfo["aps"] as! NSDictionary
            // NotificationManager.sharedInstance.handlePushNotification(byUserTapped: true, content: apnsDic)
            contentHandler(bestAttemptContent)
    
    } }
    
      // Storing APNS dictionary into database from extension
    
      func handlePushNotification(byUserTapped : Bool,content : NSDictionary) {
    
     let moduelDataDic = content.mutableCopy() as! NSMutableDictionary
    
    let entity2 =  NSEntityDescription.entity(forEntityName: "TextMessage",
                                              in: CoreDataStorage.sharedInstance.mainQueueCtxt!)
    
    let textMsg = NSManagedObject(entity: entity2!,
                                  insertInto: CoreDataStorage.sharedInstance.mainQueueCtxt) as? TextMessage
    
    let trimmedMessage = (moduelDataDic.object(forKey: "msgbody")! as AnyObject).trimmingCharacters(in: .whitespacesAndNewlines)
    
    textMsg?.message = trimmedMessage
    msgInfo?.toText = textMsg
    rosterInfo.time = composeMsgDate as Date
    rosterInfo.addToToMessageInfo(NSSet(object: msgInfo!))
    
    DispatchQueue.main.async {
    
        let context = CoreDataStorage.sharedInstance.mainQueueCtxt
        if let moc = context {
            if moc.hasChanges {
                do {
                    try moc.save()
                } catch {
                    let nserror = error as NSError
                    print("Could not save In NotficationManager \(nserror), \(nserror.userInfo)")
                }
            }
        }
    
    } }
    

    在应用程序后台模式下,我正在获取存储在上述 NotificationServiceExtension 方法中的数据,在我的结果中,我可以从 manageObject 表(messageInfo)中获取数据,但没有任何数据进入关系“let setArray = rosterInfo?.toMessageInfo”

    let resultPredicate = NSPredicate(format: "messageID == %@", 
    moduelDataDic.object(forKey: "message_id")! as! CVarArg)
    
    let messageInfoAry = 
    self.fetchMessagesFromCoreDataWithPredicate(resultPredicate: 
    resultPredicate, sortDescriptorKey: "time", isAscending: true, 
    fetchLimit: false, managedContext: self.getManageObjectContext())
    if messageInfoAry.count > 0 {
    
    let rosterInfo = (messageInfoAry[0] as! MessageInfo).toRoster
    let msgInfo = messageInfoAry[0] as! MessageInfo
    
    // Here i don't see msgInfo in this relationship but after relaunching my application i can able to see that same object
    
    let setArray = rosterInfo?.toMessageInfo 
    

    有人帮忙吗?

最佳答案

尝试将以下代码添加到您的 AppDelegate 类中并进行测试。

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    completionHandler(.newData)
    performSelector(inBackground: #selector(saveNewNotificationInBackground(userInfo:)), with: userInfo)
}

@objc func saveNewNotificationInBackground(userInfo: [AnyHashable: Any]) -> Void {
    //save notification using core data
}

关于ios - 如何从 NotificationServiceExtension 将远程通知数据保存到核心数据(数据库)中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48075346/

相关文章:

ios - 在数据库中获取关系计数的有效方法

ios - 用数字按字母顺序对数组进行排序

ios - SKProductsRequestDelegate 方法未在类内调用

swift - 无法快速更改 stackview 中的标签位置

swift - 我如何在中断状态下快速获取代码行而不是后台进程

objective-c - 在一对一关系的核心数据删除过程中查找 NSManagedObject 时出现问题

ios - 使用圆形按钮创建关卡选择屏幕

ios - SwiftUI - Canvas 超出屏幕宽度 - 应用被拒绝

ios - 如何从扩展中的函数创建 UIActivityIndi​​cator 计算属性

objective-c - 来自核心数据和外部源的模型对象