2016-06-29 173 views

回答

1

我正在寻找如何几天的做到这一点,才能够找到谁存储UILocalNotificaations的人NSUserDefaults。将这些保存在NSUserDefaults对我来说似乎是错误的,因为它应该用于小旗子。我刚才终于想出了如何在CoreData中存储通知。这是使用的Xcode 7.3.1和2.2雨燕

首先你需要在你的CoreDataModel 创建一个新的实体,然后单属性添加到它。属性应该是二进制数据我将我的表/实体命名为“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.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() 
} 

我希望这可以帮助别人谁了我试图实现这个的同样的问题。