I am a beginner at Swift and I've roughly tried to create an MVVM kinda architecture based on some tutorials However I find that the @ObservedObject variable wallpaperViewModel having some @Published value properties doesn't reflect the changes after a network operation The Network Operation works fine and I confirmed it by printing the received values to the console
Here is the required code
WallpaperViewModel
class WallpaperViewModel: ObservableObject {
@Published var wallpapers : [Wallpaper] = [Wallpaper]()
@Published var allBanners : [Banner] = [Banner]()
@Published var error: String = ""
//Handles error in requests, enum NetworkError has three cases unknown custom requestFailed
func errorHandler(error: NetworkError){
switch error {
case .custom(let customErr):
self.error = customErr
print(customErr)
case .requestFailed:
self.error = "Request Failed,Please check your internet connection"
print("Request Failed")
case .unknown:
self.error = "An unknown error occured"
print ("An unknown error occured")
case .networkNotConnected:
self.error = "Network not connected"
print ("Network not connected")
}
}
func getAllWallpapersfromApi (order: String, page: String){
NetworkingUtil().getAllWallpapers(orderBy: order, page: page){result in
switch result{
case .success(let wallpapers):
self.wallpapers = wallpapers
case .failure(let err):
self.errorHandler(error: err)
}
}
}
func getAllBanners(){
NetworkingUtil().getAllBanners(){result in
switch result{
case .success(let banners):
self.allBanners = banners
print("allBanners: (in VM)", banners)
case .failure(let error):
self.errorHandler(error: error)
}
}
}
}
And here is my main view
struct ContentView: View {
@ObservedObject var wallpaperViewModel = WallpaperViewModel()
@State private var selectedTab = 0
var body: some View {
VStack{
if(wallpaperViewModel.error.isEmpty){
TabView(selection: $selectedTab){
if(wallpaperViewModel.allBanners.count == 0){
Text("Loading..")
}
else{
ForEach(0..<wallpaperViewModel.allBanners.count){ bannerIndex in
//let banner = banners[bannerIndex]
Image("cover-cheetah")
.resizable()
.scaledToFill()
.frame(height:selectedTab == bannerIndex ? 230 : 180)
.cornerRadius(12)
}
}
}
.frame(height: 230)
.tabViewStyle(PageTabViewStyle())
.animation(.easeOut)
.padding(.horizontal)
}
else{
Text("\(wallpaperViewModel.error)")
}
}
.onAppear{
self.wallpaperViewModel.getAllBanners()
print("allBanners in ContentView",wallpaperViewModel.allBanners)
self.wallpaperViewModel.getAllWallpapersfromApi(order: "created", page: String(0))
print("allWallpapers in ContentView",wallpaperViewModel.wallpapers)
}
Here is the values logged to the console
And here is the output on the Simulator