繁体   English   中英

如何在CoreData中保存UILocalNotifications

[英]How Save UILocalNotifications in CoreData

答案在下面,图像在这里:

在此处输入图片说明

我搜索了几天的方法,只能找到在NSUserDefaults中存储UILocalNotificaations 将它们保存在NSUserDefaults中对我来说似乎是错误的,因为它应该用于小标志。 我刚才终于想出了如何在CoreData中存储通知。 这是使用Xcode 7.3.1和Swift 2.2

首先,您需要在CoreDataModel中创建一个新实体 ,然后向其添加单个属性。 该属性应为Binary Data类型,我将表/实体命名为“ ManagedFiredNotifications”,将属性命名为“ notification”。 它应该看起来像这样:

图片在上面的问题中链接。

接下来,您需要向UILocalNotification添加扩展,它应如下所示:

extension UILocalNotification { 
   func save() -> Bool {
      let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
      let firedNotificationEntity = NSEntityDescription.insertNewObjectForEntityForName("ManagedFiredNotifications", inManagedObjectContext: appDelegate!.managedObjectContext)

      guard appDelegate != nil else {
         return false
      }

      let data = NSKeyedArchiver.archivedDataWithRootObject(self)

      firedNotificationEntity.setValue(data, forKey: "notification")

      do {
         try appDelegate!.managedObjectContext.save()
         return true
      } catch {
         return false
      }
   }
}

现在要保存通知,您需要做的就是打电话

UILocalNotification.save()

在通知上,您要保存。 我的通知被命名为“ notification”,因此我将调用notification.save()

要检索通知,您需要这样的方法

func getLocalFiredNotifications() -> [UILocalNotification]? {
    let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)!.managedObjectContext
    let firedNotificationFetchRequest = NSFetchRequest(entityName: "ManagedFiredNotifications")
    firedNotificationFetchRequest.includesPendingChanges = false

    do {
        let fetchedFiredNotifications = try managedObjectContext.executeFetchRequest(firedNotificationFetchRequest)
        guard fetchedFiredNotifications.count > 0 else {
            return nil
        }


        var firedNotificationsToReturn = [UILocalNotification]()
        for managedFiredNotification in fetchedFiredNotifications {

            let notificationData = managedFiredNotification.valueForKey("notification") as! NSData
            let notificationToAdd = NSKeyedUnarchiver.unarchiveObjectWithData(notificationData) as! UILocalNotification

            firedNotificationsToReturn.append(notificationToAdd)
        }
        return firedNotificationsToReturn
    } catch {
        return nil
    }

}

请注意,这将返回一个UILocalNotifications数组。

当您打算删除其中一些然后再次存储列表时,在检索这些文件时,应在获得它们时将其删除,如下所示:

func loadFiredNotifications() {
    let notifications = StudyHelper().getLocalFiredNotifications()
    if notifications != nil {
        firedNotifications = notifications!
    } else {
        // throw an error or log it
    }
    classThatRemoveMethodIsIn().removeFiredLocalNotifications()
}

我希望这可以帮助遇到与我尝试实现此问题相同的问题的人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM