I’m constructing an eCommerce app with SwiftUI that should retrieve some information from a server earlier than loading most of the views. It is type of common, however I’m truthfully questioning one of the best ways to retrieve and retailer this information.
For instance, on the house web page the app requests the server for the names of some pictures to be displayed, after which makes use of AsyncImage
to load every picture from the server. Presently I’m making a @State
variable inside the view to retailer the picture names, and loading the info in a .process
:
struct CoverImagesTabView: View {
@State var coverImageNames: [String] = []
var physique: some View {
TabView {
ForEach(coverImageNames, id: .self) { coverImage in
CoverImageView(coverImage: coverImage)
.padding(.high, 10)
.padding(.horizontal, 15)
} //: LOOP
} //: TAB
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .at all times))
.process {
await getCoverImageNames { imageNames in
coverImageNames = imageNames
}
}
}
}
with the getCoverImageNames
perform trying like
import Alamofire
func getCoverImageNames(_ callback: @escaping (_ decoded: [String]) -> Void) async {
AF.request("http://(serverIP)/api/choices/advertising and marketing/coverImages")
.responseDecodable(of: [String].self) { response in
if response.worth != nil {
callback(response.worth ?? [])
print("Cowl picture names retrieved")
} else {
print("Couldn't entry cowl picture names")
}
}
}
The coverImageNames
are then used inside the CoverImageView
. I plan to make use of the identical methodology to retrieve a product checklist (an array of customized product
objects) earlier than loading a product checklist view, and with different information/views inside the app.
This methodology appears just a little clunky to me, largely as a result of it makes this name to the API to set the worth of coverImageNames
each time the view is reloaded; this information (together with a variety of different information such because the product checklist) actually solely must be loaded as soon as, at each app startup. What’s one of the best ways to go about this?
I thought-about utilizing Core Information to save lots of the info from the server, however that appears approach overkill.
I’ve thought-about creating a category that conforms to ObservableObject
and passing an occasion of it as a @StateObject
to this view, and it solves the problem, however this nonetheless feels off, creating a complete new class simply to characterize a [String]
particularly in order that it solely masses as soon as.
Maybe I’m unsuitable and that is one of the best ways to load app information from the server earlier than views load at startup, however being new to Swift I simply wished to see if I used to be lacking one thing. I wish to know what the popular methodology or the very best follow is for this earlier than transferring ahead, and I am not discovering any definitive solutions on the market. Any solutions or extra assets could be nice.