I have implemented core data with required function. I am trying to call function into view , when we do not have data into core data , that time I am making network call and save the data into core data. I am following MVVM Architecture pattern. Inside the view I also have search functionality as well. The problem is when I try to call the save function I am getting following error ..
Type '()' cannot conform to 'View'
I am expecting when we make network call that time , it should configure the data into list and also save it into core data storage..
Here is the core data function.
import Foundation
import CoreData
class CoreDataViewModel: ObservableObject {
let persistentContainer: NSPersistentContainer
init() {
persistentContainer = NSPersistentContainer(name: "ProductDataManager")
persistentContainer.loadPersistentStores { (description, error) in
if let error = error {
print("Core Data Store failed \(error.localizedDescription)")
}
}
}
func saveProduct(products: Product) {
let product = ProductEntity(context: persistentContainer.viewContext)
product.id = Int16(products.id)
product.title = products.title
product.price = Int32(products.price)
product.quantity = Int16(products.quantity)
product.total = Int32(products.total)
product.discountPercentage = products.discountPercentage
product.discountedPrice = Int32(products.discountedPrice)
do {
try persistentContainer.viewContext.save()
} catch {
print("Failed to save movie \(error)")
}
}
}
Here is my view Model code .. It has dependency on ProductRepository if required I can add that code as well ..
import Foundation
protocol ProductListViewModelAction: ObservableObject {
func getProductList(urlStr: String) async
}
@MainActor
final class ProductListViewModel {
@Published private(set) var productLists: [Product] = []
@Published private var filteredProductLists: [Product] = []
@Published private(set) var customError: NetworkError?
private let repository: ProductRepository
init(repository: ProductRepository) {
self.repository = repository
}
}
extension ProductListViewModel: ProductListViewModelAction {
func getProductList(urlStr: String) async {
guard let url = URL(string: urlStr) else {
self.customError = NetworkError.invalidURL
return
}
do {
let lists = try await repository.getList(for: url)
productLists = lists.carts.first?.products ?? []
} catch {
customError = error as? NetworkError
}
}
}
extension ProductListViewModel {
func performSearch(keyword: String) {
filteredProductLists = self.productLists.filter {
$0.title.localizedCaseInsensitiveContains(keyword)
}
}
var productList: [Product] {
filteredProductLists.isEmpty ? productLists: filteredProductLists
}
}
Here is my view code ..
import SwiftUI
struct ProductListView: View {
@StateObject var viewModel = ProductListViewModel(repository: ProductRepositoryImplementation(networkManager: NetworkManager()))
@StateObject var coreData = CoreDataViewModel()
@State var searchText = ""
var body: some View {
NavigationStack {
VStack {
if viewModel.productLists.count > 0 {
List(viewModel.productList, id: \.self) { product in
NavigationLink(destination: ProductDetailsView(product: product)) {
ProductListViewCell(productData: product)
coreData.saveProduct(products: product) // error is here ..
}
} .listStyle(.grouped)
}
}
}
.searchable(text: $searchText)
.onChange(of: searchText, perform: viewModel.performSearch)
.navigationTitle(Text("Product List"))
}.task {
await getDataFromAPI()
}
.refreshable {
await getDataFromAPI()
}
}
func getDataFromAPI() async {
await viewModel.getProductList(urlStr: NetworkURL.productUrl)
}
}
Here is the screenshot of the error ..
It's a common mistake when someone starts using SwiftUI: attempting to call a function where only View types are allowed.
You can easily fix this by calling the function when the view is appearing:
List(viewModel.productList, id: \.self) { product in
NavigationLink(destination: ProductDetailsView(product: product)) {
ProductListViewCell(productData: product)
.onAppear {
coreData.saveProduct(products: product)
}
}
}
However due to the behavior of Lists, it may appear multiple times while scrolling through the view. I would check whether it's already saved or not to prevent unnecessary save actions.
Just a note: the Product has an 'id' variable, so you can conform it to the Identifiable protocol. After that, you don't need to specify 'id' in List or ForEach.
List(viewModel.productList)