[ad_1]
I’ve accomplished code and performance however making an attempt to put in writing unit check circumstances tried few instance over some tutorial however not getting success, simply to start out I wish to know the way ought to i write check case for API and easy UI. On the lookout for simply easy setup based mostly on that I’ll strive myself to put in writing different.
Additionally I’ve core information mannequin..Can we write check circumstances for that too?
API name
import Basis
import CoreData
import SwiftUI
class HomeViewModel: ObservableObject {
@Printed var outcomes = [ResultItem]()
@Printed var coreDM: PersistenceController = PersistenceController()
func getData() {
guard let gUrl = URL(
string: "https://api.artic.edu/api/v1/artworks"
) else { return }
Process {
do {
let (information, _) = strive await URLSession.shared.information(from: gUrl)
let response = strive JSONDecoder()
.decode(ResponseData.self, from: information)
DispatchQueue.fundamental.async { [weak self] in
self?.outcomes = response.information ?? []
self?.coreDM.deleteOldResult()
self?.outcomes.forEach{
self?.coreDM.saveResult(title: $0.title ?? "")
}
}
} catch {
print("*** ERROR ***")
}
}
}
}
UI
import SwiftUI
import CoreData
struct ContentView: View {
@Setting(.managedObjectContext) personal var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: Item.title, ascending: true)],
animation: .default)
personal var gadgets: FetchedResults<Merchandise>
@StateObject personal var viewModel = HomeViewModel()
var physique: some View {
GeometryReader { geometry in
NavigationView {
ScrollView {
LazyVGrid(columns: Array(repeating: .init(.versatile()),
rely: UIDevice.present.userInterfaceIdiom == .pad ? 8 : 4)) {
ForEach(gadgets) { merchandise in
NavigationLink(vacation spot: {
DetailView(information: merchandise.title ?? "")
}, label: {
SearchResultRow(merchandise: merchandise)
})
}
}
}.padding([.horizontal], 5)
}
.onAppear(carry out: {
viewModel.getData()
})
}
}
}
struct SearchResultRow: View {
@ObservedObject var merchandise: Merchandise
var physique: some View {
HStack {
RoundedRectangle(cornerRadius: 1).fill(.yellow)
.body(maxWidth: .infinity).aspectRatio(1, contentMode: .match)
.overlay(Textual content(merchandise.title ?? ""))
}.padding(.all, 2)
.background(Coloration.crimson)
}
}
Knowledge mannequin
import Basis
// MARK: - Predominant Object
struct ResponseData: Codable, Hashable {
let information: [ResultItem]?
}
// MARK: - Consequence Merchandise
struct ResultItem: Codable, Hashable {
var id: Double?
var title: String?
}
#if DEBUG
// MARK: - Instance Merchandise
extension ResultItem {
static var instance: ResultItem {
ResultItem(
id: 13124,
title: "TestData"
)
}
}
#endif
[ad_2]
