How to update FetchRequest with predicate in SwiftUI

Issue #621

Make subview that accepts FetchRequest. Trigger search by setting property

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
struct SideView: View {
@Environment(\.managedObjectContext)
var context

@State var search: Search?

var body: some View {
VStack(alignment: .leading) {
SearchView(
onSearch: self.onSearch
)
InsideListView(fetchRequest: makeFetchRequest())
}
}

private func makeFetchRequest() -> FetchRequest<Book> {
let predicate: NSPredicate?
if let search = search {
let textPredicate = NSPredicate(format: "string CONTAINS[cd] %@", search.text)
let appPredicate = NSPredicate(format: "appName == %@", search.app)
let typePredicate = NSPredicate(format: "type == %@", search.type)

var predicates: [NSPredicate] = []
if search.text.count >= 3 {
predicates.append(textPredicate)
}

if search.app != Constants.all {
predicates.append(appPredicate)
}

if search.type != Constants.all {
predicates.append(typePredicate)
}

predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
} else {
predicate = nil
}

return FetchRequest<Book>(
entity: Book.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \Book.date, ascending: false)
],
predicate: predicate
)
}

private func onSearch(_ search: Search) {
if search.text.count < 3 && search.type != Constants.all && search.app != Constants.all {
self.search = nil
} else {
self.search = search
}
}
}

private struct InsideListView: View {
@Environment(\.managedObjectContext)
var context

var fetchRequest: FetchRequest<Book>

var body: some View {
List(items) {
ForEach
}
}

private var items: FetchedResults<Book> {
fetchRequest.wrappedValue
}
}
© 2020 onmyway133 All Rights Reserved.
Theme by hiero