Merge pull request #110 from writeas/keep-local-posts-on-logout

Keep local posts on logging out
This commit is contained in:
Angelo Stavrow 2020-10-27 13:12:56 -04:00 committed by GitHub
commit 1170caaf4a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 36 additions and 4 deletions

View File

@ -55,6 +55,7 @@ struct AccountLoginView: View {
.padding()
} else {
Button(action: {
hideKeyboard()
model.login(
to: URL(string: server)!,
as: username, password: password

View File

@ -2,6 +2,10 @@ import SwiftUI
struct AccountLogoutView: View {
@EnvironmentObject var model: WriteFreelyModel
@Environment(\.managedObjectContext) var moc
@State private var isPresentingLogoutConfirmation: Bool = false
@State private var editedPostsWarningString: String = ""
var body: some View {
VStack {
@ -15,10 +19,35 @@ struct AccountLogoutView: View {
Text("Log Out")
})
}
.actionSheet(isPresented: $isPresentingLogoutConfirmation, content: {
ActionSheet(
title: Text("Log Out?"),
message: Text("\(editedPostsWarningString)You won't lose any local posts. Are you sure?"),
buttons: [
.destructive(Text("Log Out"), action: {
model.logout()
}),
.cancel()
]
)
})
}
func logoutHandler() {
model.logout()
let request = WFAPost.createFetchRequest()
request.predicate = NSPredicate(format: "status == %i", 1)
do {
let editedPosts = try LocalStorageManager.persistentContainer.viewContext.fetch(request)
if editedPosts.count == 1 {
editedPostsWarningString = "You'll lose unpublished changes to \(editedPosts.count) edited post. "
}
if editedPosts.count > 1 {
editedPostsWarningString = "You'll lose unpublished changes to \(editedPosts.count) edited posts. "
}
} catch {
print("Error: failed to fetch cached posts")
}
self.isPresentingLogoutConfirmation = true
}
}

View File

@ -281,7 +281,7 @@ private extension WriteFreelyModel {
DispatchQueue.main.async {
self.account.logout()
LocalStorageManager().purgeUserCollections()
self.posts.purgeAllPosts()
self.posts.purgePublishedPosts()
}
} catch {
print("Something went wrong purging the token from the Keychain.")
@ -296,7 +296,7 @@ private extension WriteFreelyModel {
DispatchQueue.main.async {
self.account.logout()
LocalStorageManager().purgeUserCollections()
self.posts.purgeAllPosts()
self.posts.purgePublishedPosts()
}
} catch {
print("Something went wrong purging the token from the Keychain.")

View File

@ -27,13 +27,15 @@ class PostListModel: ObservableObject {
LocalStorageManager().saveContext()
}
func purgeAllPosts() {
func purgePublishedPosts() {
userPosts = []
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "WFAPost")
fetchRequest.predicate = NSPredicate(format: "status != %i", 0)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try LocalStorageManager.persistentContainer.viewContext.executeAndMergeChanges(using: deleteRequest)
loadCachedPosts()
} catch {
print("Error: Failed to purge cached posts.")
}