55// Created by Sameer Nawaz on 18/09/21.
66//
77
8- import Foundation
8+ import SwiftUI
9+ import CoreData
910
1011class ArticleViewModel : ObservableObject {
1112
@@ -14,4 +15,49 @@ class ArticleViewModel: ObservableObject {
1415 init ( model: NewsModel ) {
1516 self . model = model
1617 }
18+
19+ func isBookmarked( _ articles: FetchedResults < ArticleCD > ) -> Bool {
20+ for article in articles {
21+ if article. url == model. url? . absoluteString {
22+ return true
23+ }
24+ }
25+ return false
26+ }
27+
28+ func bookmarkArticle(
29+ _ articles: FetchedResults < ArticleCD > ,
30+ _ moc: NSManagedObjectContext
31+ ) {
32+ for article in articles {
33+ if article. url == model. url? . absoluteString {
34+ removeBookmark ( article, moc)
35+ return
36+ }
37+ }
38+ addBookmark ( moc)
39+ }
40+
41+ private func addBookmark( _ moc: NSManagedObjectContext ) {
42+ let articleObj = ArticleCD ( context: moc)
43+ articleObj. id = UUID ( )
44+ articleObj. createdAt = Date ( )
45+ articleObj. sourceId = model. id? . rawValue
46+ articleObj. author = model. author
47+ articleObj. content = model. content
48+ articleObj. desc = model. description
49+ articleObj. publishedAt = model. publishedAt
50+ articleObj. title = model. title
51+ articleObj. url = model. url? . absoluteString
52+ articleObj. urlToImage = model. urlToImage? . absoluteString
53+ do { try moc. save ( ) }
54+ catch { print ( error. localizedDescription) }
55+ }
56+
57+ private func removeBookmark( _ article: ArticleCD , _ moc: NSManagedObjectContext ) {
58+ moc. delete ( article)
59+ do {
60+ try moc. save ( )
61+ } catch { print ( error. localizedDescription) }
62+ }
1763}
0 commit comments