From 66e8fce48851f0d97d74bd5d124a9878d3b36eec Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Fri, 11 Jun 2021 10:19:43 -0400 Subject: [PATCH] Fix crash when conversation VC tries to restore from unloaded status --- .../ConversationTableViewController.swift | 30 ++++++++++++++++--- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/Tusker/Screens/Conversation/ConversationTableViewController.swift b/Tusker/Screens/Conversation/ConversationTableViewController.swift index ac3928b5..dec523a0 100644 --- a/Tusker/Screens/Conversation/ConversationTableViewController.swift +++ b/Tusker/Screens/Conversation/ConversationTableViewController.swift @@ -131,7 +131,31 @@ class ConversationTableViewController: EnhancedTableViewController { let initialImage = showStatusesAutomatically ? ConversationTableViewController.hidePostsImage : ConversationTableViewController.showPostsImage visibilityBarButtonItem = UIBarButtonItem(image: initialImage, style: .plain, target: self, action: #selector(toggleVisibilityButtonPressed)) navigationItem.rightBarButtonItem = visibilityBarButtonItem - + + loadMainStatus() + } + + private func loadMainStatus() { + if let mainStatus = mastodonController.persistentContainer.status(for: mainStatusID) { + self.mainStatusLoaded(mainStatus) + } else { + let request = Client.getStatus(id: mainStatusID) + mastodonController.run(request) { (response) in + switch response { + case let .success(status, _): + let viewContext = self.mastodonController.persistentContainer.viewContext + self.mastodonController.persistentContainer.addOrUpdate(status: status, incrementReferenceCount: false, context: viewContext) { (statusMO) in + self.mainStatusLoaded(statusMO) + } + + case .failure(_): + fatalError() + } + } + } + } + + private func mainStatusLoaded(_ mainStatus: StatusMO) { let mainStatusItem = Item.status(id: mainStatusID, state: mainStatusState) var snapshot = NSDiffableDataSourceSnapshot() @@ -139,12 +163,10 @@ class ConversationTableViewController: EnhancedTableViewController { snapshot.appendItems([mainStatusItem], toSection: .statuses) dataSource.apply(snapshot, animatingDifferences: false) - guard let mainStatus = self.mastodonController.persistentContainer.status(for: self.mainStatusID) else { - fatalError("Missing cached status \(self.mainStatusID)") - } let mainStatusInReplyToID = mainStatus.inReplyToID mainStatus.incrementReferenceCount() + // todo: it would be nice to cache these contexts let request = Status.getContext(mainStatusID) mastodonController.run(request) { response in guard case let .success(context, _) = response else { fatalError() }