SwiftUI MVVM with Networking
It can’t be that hard!
--
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 12.1, and Swift 5.3
If you want to develop any sort of `SwiftUI
` application you
Prerequisites:
- You will be expected to make a Single View SwiftUI Application in Swift.
Terminology
SwiftUI: A simple way to build user interfaces Across Apple platforms
The motivation
You will need to create nicely featured Apps. They are going to (probably) make network calls. This means that you need to develop an architecture that is going to support this in your development.
Let’s go MVVM
!
The basic architecture
The Main view (which I’ve creatively called ContentView
) is instantiated with a view model which is creatively called ContentViewModel
.
Therefore in the SceneDelegate
contentView is created with let contentView = ContentView(viewModel: ContentViewModel())
.
My ContentView
isn’t going to do anything in this case, apart from creating a reference to the view model
struct ContentView: View {
@ObservedObject var viewModel: ContentViewModel
init(viewModel: ContentViewModel) {
self.viewModel = viewModel
}
var body: some View {
NavigationView {
List {
ForEach(viewModel.users, id: \.self) {
user in
Text("\(user.title)")
}
}
.navigationBarTitle("User")
.listStyle(GroupedListStyle())
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(viewModel: ContentViewModel())
}
}
We are going to have the following view model
class ContentViewModel: ObservableObject {
@Published var users: [User] = []
var res: AnyCancellable?
private var networkManager: AnyNetworkManager<URLSession>?
init() {
self.networkManager = AnyNetworkManager(manager…