2016-06-29 171 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() 
} 

我希望這可以幫助別人誰了我試圖實現這個的同樣的問題。