Update watch history using background context

This commit is contained in:
Arkadiusz Fal 2022-06-08 00:15:15 +02:00
parent 359e39b16f
commit 58de661d96
2 changed files with 32 additions and 24 deletions

View File

@ -32,17 +32,23 @@ extension PlayerModel {
let time = backend.currentTime
let seconds = time?.seconds ?? 0
let watch: Watch!
let watchFetchRequest = Watch.fetchRequest()
watchFetchRequest.predicate = NSPredicate(format: "videoID = %@", id as String)
let results = try? context.fetch(watchFetchRequest)
let results = try? backgroundContext.fetch(watchFetchRequest)
backgroundContext.perform { [weak self] in
guard let self = self else {
return
}
let watch: Watch!
if results?.isEmpty ?? true {
if seconds < 1 {
return
}
watch = Watch(context: context)
watch = Watch(context: self.backgroundContext)
watch.videoID = id
} else {
watch = results?.first
@ -52,7 +58,7 @@ extension PlayerModel {
}
}
if let seconds = playerItemDuration?.seconds {
if let seconds = self.playerItemDuration?.seconds {
watch.videoDuration = seconds
}
@ -64,7 +70,8 @@ extension PlayerModel {
watch.watchedAt = Date()
try? context.save()
try? self.backgroundContext.save()
}
}
func removeWatch(_ watch: Watch) {

View File

@ -80,6 +80,7 @@ final class PlayerModel: ObservableObject {
}
}}
var context: NSManagedObjectContext = PersistenceController.shared.container.viewContext
var backgroundContext = PersistenceController.shared.container.newBackgroundContext()
@Published var playingInPictureInPicture = false
var pipController: AVPictureInPictureController?