Fetch user posts into CoreData on launch, purge from database on logout

This commit is contained in:
Angelo Stavrow 2020-09-04 16:56:14 -04:00
parent 3bdc08f067
commit 9dd149c59d
No known key found for this signature in database
GPG Key ID: 1A49C7064E060EEE
3 changed files with 26 additions and 5 deletions

View File

@ -1,5 +1,6 @@
import Foundation
import WriteFreely
import CoreData
struct PostStore {
var posts: [Post]
@ -14,6 +15,16 @@ struct PostStore {
mutating func purgeAllPosts() {
posts = []
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "WFAPost")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try PersistenceManager.persistentContainer.persistentStoreCoordinator.execute(
deleteRequest, with: PersistenceManager.persistentContainer.viewContext
)
} catch {
print("Error: Failed to purge cached posts.")
}
}
mutating func update(_ post: Post) {

View File

@ -187,9 +187,6 @@ private extension WriteFreelyModel {
}
func fetchUserCollectionsHandler(result: Result<[WFCollection], Error>) {
DispatchQueue.main.async {
self.collections.loadCachedUserCollections()
}
do {
let fetchedCollections = try result.get()
for fetchedCollection in fetchedCollections {
@ -227,9 +224,22 @@ private extension WriteFreelyModel {
post = Post(wfPost: fetchedPost)
}
fetchedPostsArray.append(post)
let managedPost = WFAPost(context: PersistenceManager.persistentContainer.viewContext)
managedPost.postId = fetchedPost.postId
managedPost.slug = fetchedPost.slug
managedPost.appearance = fetchedPost.appearance
managedPost.language = fetchedPost.language
managedPost.rtl = fetchedPost.rtl ?? false
managedPost.createdDate = fetchedPost.createdDate
managedPost.updatedDate = fetchedPost.updatedDate
managedPost.title = fetchedPost.title
managedPost.body = fetchedPost.body
managedPost.collectionAlias = fetchedPost.collectionAlias
managedPost.status = 2 // 0 = local, 1 = edited, 2 = published
}
DispatchQueue.main.async {
self.store.updateStore(with: fetchedPostsArray)
PersistenceManager().saveContext()
}
} catch {
print(error)

View File

@ -7,12 +7,12 @@
<key>WriteFreely-MultiPlatform (iOS).xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
<integer>1</integer>
</dict>
<key>WriteFreely-MultiPlatform (macOS).xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>1</integer>
<integer>0</integer>
</dict>
</dict>
</dict>