From d659063897b05d46a1620f071dc52eb43bf1732e Mon Sep 17 00:00:00 2001 From: Arkadiusz Fal Date: Wed, 8 Jun 2022 00:15:15 +0200 Subject: [PATCH] Update watch history using background context --- Model/HistoryModel.swift | 55 +++++++++++++++++++--------------- Model/Player/PlayerModel.swift | 1 + 2 files changed, 32 insertions(+), 24 deletions(-) diff --git a/Model/HistoryModel.swift b/Model/HistoryModel.swift index 0867bb0f..ff920cbb 100644 --- a/Model/HistoryModel.swift +++ b/Model/HistoryModel.swift @@ -32,39 +32,46 @@ 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) - if results?.isEmpty ?? true { - if seconds < 1 { + backgroundContext.perform { [weak self] in + guard let self = self else { return } - watch = Watch(context: context) - watch.videoID = id - } else { - watch = results?.first - if !Defaults[.resetWatchedStatusOnPlaying], watch.finished { - return + let watch: Watch! + + if results?.isEmpty ?? true { + if seconds < 1 { + return + } + watch = Watch(context: self.backgroundContext) + watch.videoID = id + } else { + watch = results?.first + + if !Defaults[.resetWatchedStatusOnPlaying], watch.finished { + return + } } + + if let seconds = self.playerItemDuration?.seconds { + watch.videoDuration = seconds + } + + if finished { + watch.stoppedAt = watch.videoDuration + } else if seconds.isFinite, seconds > 0 { + watch.stoppedAt = seconds + } + + watch.watchedAt = Date() + + try? self.backgroundContext.save() } - - if let seconds = playerItemDuration?.seconds { - watch.videoDuration = seconds - } - - if finished { - watch.stoppedAt = watch.videoDuration - } else if seconds.isFinite, seconds > 0 { - watch.stoppedAt = seconds - } - - watch.watchedAt = Date() - - try? context.save() } func removeWatch(_ watch: Watch) { diff --git a/Model/Player/PlayerModel.swift b/Model/Player/PlayerModel.swift index 5513fdf4..cccde5e4 100644 --- a/Model/Player/PlayerModel.swift +++ b/Model/Player/PlayerModel.swift @@ -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?