How to create MVP and MVVM architecture in iOS Xcode project - ios

I have read articles about MVC, MVP and MVVM architecture but I am not cleat about how to create each architecture in my iOS app. Which classes/controller files I need to use to make for each architecture. What is the difference between them if we are using with Storyboard/Xib/Programmatically?
As I am using Xcode default MVC structure for iOS apps but I want to create my new project with MVVM structure but I am not sure how to create that structure.
Any help would be highly appreciated.
Thanks in advance.

This is an oversimplification of the many variants of these design patterns, but this is how I like to think about the differences between the two.
MVC
MVP
MVVM
for more information you can look at here

MVVM architecture in iOS can be easily implemented without using third party dependencies. For data binding, we can use a simple combination of Closure and didSet to avoid third-party dependencies.
public final class Observable<Value> {
private var closure: ((Value) -> ())?
public var value: Value {
didSet { closure?(value) }
}
public init(_ value: Value) {
self.value = value
}
public func observe(_ closure: #escaping (Value) -> Void) {
self.closure = closure
closure(value)
}
}
An example of data binding from ViewController:
final class ExampleViewController: UIViewController {
private func bind(to viewModel: ViewModel) {
viewModel.items.observe(on: self) { [weak self] items in
self?.tableViewController?.items = items
// self?.tableViewController?.items = viewModel.items.value // This would be Momory leak. You can access viewModel only with self?.viewModel
}
// Or in one line:
viewModel.items.observe(on: self) { [weak self] in self?.tableViewController?.items = $0 }
}
override func viewDidLoad() {
super.viewDidLoad()
bind(to: viewModel)
viewModel.viewDidLoad()
}
}
protocol ViewModelInput {
func viewDidLoad()
}
protocol ViewModelOutput {
var items: Observable<[ItemViewModel]> { get }
}
protocol ViewModel: ViewModelInput, ViewModelOutput {}
final class DefaultViewModel: ViewModel {
let items: Observable<[ItemViewModel]> = Observable([])
// Implmentation details...
}
Later it can be replaced with SwiftUI and Combine (when a minimum iOS version in of your app is 13)
In this article, there is a more detailed description of MVVM
https://tech.olx.com/clean-architecture-and-mvvm-on-ios-c9d167d9f5b3

In MVVM, the View (which is really the UIViewController) asks the View Model for information.
textLabel.text = viewModel.textToShow
The view model has a representation of everything needed to construct the UI. The View asks the View Model for those values (like, what string to show).
In MVP, the Presenter tells the View what to do.
view.showText(textToShow)
The view controller implements a protocol that translates this request into view controller specifics:
func showText(_ text: String) {
textLabel.text = text
}
Here's an example of MVP: https://stackoverflow.com/a/54499119/246895.

Related

Good strategy for replacing parts of functionality in iOS ViewControllers

I have VCs in an iOS app which have quite a lot of UI controls. I would now need to replace or "mock" some of these controls when in a specific state. In some cases this would be just disabling button actions, but in some cases the actions that happen need to be replaced with something completely different.
I don't really like the idea of having this sort of check littered all around the codebase.
if condition {
...Special/disabled functionality
} else {
...Normal functionality
}
In Android, I can just subclass each Fragment/Activity and build the functionality there, and then doing the if/else when inserting Fragments or launching activities.
But on iOS with Storyboards/IBActions and Segues, UIs and VCs are really tightly coupled. You either end up duplicating UI views or adding a lot of finicky code to already large VCs.
What would be the best way to handle this in iOS?
Sample code of what I want to avoid doing:
//Before:
class SomeViewController : UIViewController {
#IBAction onSomeButton() {
checkSomeState()
doANetworkRequest(() -> {
someCompletionHandler()
updatesTheUI()
}
updateTheUIWhileLoading()
}
#IBAction onSomeOtherButton() {
checkAnotherState()
updateUI()
}
}
//After:
class SomeViewController : UIViewController {
#IBAction onSomeButton() {
if specialState {
doSomethingSimpler()
} else {
checkSomeState()
doANetworkRequest(() -> {
someCompletionHandler()
updatesTheUI()
}
updateTheUIWhileLoading()
}
}
#IBAction onSomeOtherButton() {
if specialState {
return // Do nothing
} else {
checkAnotherState()
updateUI()
}
}
}
I'd suggest using the MVVM (Model - View - ViewModel) pattern. You pass the ViewModel to your controller and delegate all actions to it. You can also use it to style your views and decide if some of them should be hidden or disabled, etc.
Let's image a shopping app in which your pro users get a 10% discount and can use a free-shipping option.
protocol PaymentScreenViewModelProtocol {
var regularPriceString: String { get }
var discountedPriceString: String? { get }
var isFreeShippingAvailable: Bool { get }
func userSelectedFreeShipping()
func buy()
}
class StandardUserPaymentScreenViewModel: PaymentScreenViewModelProtocol {
let regularPriceString: String = "20"
let discountedPriceString: String? = nil
let isFreeShippingAvailable: Bool = false
func userSelectedFreeShipping() {
// standard users cannot use free shipping!
}
func buy() {
// process buying
}
}
class ProUserPaymentScreenViewModel: PaymentScreenViewModelProtocol {
let regularPriceString: String = "20"
let discountedPriceString: String? = "18"
let isFreeShippingAvailable: Bool = true
func userSelectedFreeShipping() {
// process selection of free shipping
}
func buy() {
// process buying
}
}
class PaymentViewController: UIViewController {
#IBOutlet weak var priceLabel: UILabel!
#IBOutlet weak var discountedPriceLabel: UILabel!
#IBOutlet weak var freeShippingButton: UIButton!
var viewModel: PaymentScreenViewModelProtocol
override func viewDidLoad() {
super.viewDidLoad()
priceLabel.text = viewModel.regularPriceString
discountedPriceLabel.text = viewModel.discountedPriceString
freeShippingButton.isHidden = !viewModel.isFreeShippingAvailable
}
#IBAction func userDidPressFreeShippingButton() {
viewModel.userSelectedFreeShipping()
}
#IBAction func userDidPressBuy() {
viewModel.buy()
}
}
This approach let's you decouple your logic from your views. It's also easier to test this logic.
One thing to consider and decide is the approach as to how to inject the view model into the view controller. I can see three possibilities :
Via init - you provide a custom initializer requiring to pass the view model. This will mean you won't be able to use segue's or storyboards (you will be able to use xibs). This will let your view model be non-optional.
Via property setting with default implementation - if you provide some form of default/empty implementation of your view model you could use it as a default value for it, and set the proper implementation later (for example in prepareForSegue). This enables you to use segues, storyboards and have the view model be non-optional (it just adds the overhead of having an extra empty implementation).
Via property setting without default implementation - this basically means that your view model will need to be an optional and you will have to check for it almost everytime you access it.

How can I use Rx Swift PublishRelay with no type just for onCompleted() event?

I have this view model in my code:
import RxSwift
protocol ViewModelInput {
func buttonTouched()
}
protocol ViewModelOutput {
var done : PublishRelay<Bool> { get set }
}
protocol ViewModelType {
var inputs: ViewModelInput { get }
var outputs: ViewModelOutput { get }
}
public final class ViewModel: ViewModelInput, ViewModelOutput, ViewModelType {
var inputs: ViewModelInput { return self }
var outputs: ViewModelOutput { return self }
internal var done = PublishRelay<Bool>.init()
init() {}
func buttonTouched() {
self.outputs.done.accept(true)
}
}
And I'm using it's "output" like this:
// Somewhere else in my app
viewModel.outputs.done
.asObservable()
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] _ in
// whatever
}).disposed(by: disposeBag)
To be honest I don't need that Boolean value with PublishRelay. I don't even need onNext() event. All I need is to notify my coordinator (part of app that uses this view model) about onCompleted(). However there is still some <Bool> generic type added to my output. I don't need any of that. Is there any cleaner way to achieve that?
I though about traits like Completable but as far as I understand I need to emit completed-event inside create() method or use Completable.empty(). Or maybe I don't understand traits that good, I don't know.
Any ideas?
I haven't done any RxSwift in a while, but have you tried making the type PublishRelay<Void>? Once you do that you can just pass () to outputs.done.accept(()) in your buttonTouched() method and not have to worry about passing arbitrary information that isn't needed
I think #Steven0351 is right with the < Void> approach. Just 2 little things:
It should also work by terminating the subject instead of emitting a Void value. It looks cleaner in the subscription as well.
I guess you are subscribing your outputs.done subject in the UI. In that case you might want to use Drivers. That way there's no need to specify observation on main scheduler (among other Drivers advantages).
ViewModel
internal var done = PublishRelay<Void>.init()
func buttonTouched() {
self.outputs.done.onCompleted()
}
ViewController
viewModel.outputs.done
.asDriver()
.drive(onCompleted: { [weak self] in
// whatever
}).disposed(by: disposeBag)

RxSwift network status observable

I have a method 'getProducts' in my view model:
struct MyViewModel {
func getProducts(categoryId: Int) -> Observable<[Product]> {
return api.products(categoryId: categoryId)
}
var isRunning: Observable <Bool> = {
...
}
}
api.products is a private variable which uses URLSession rx extension: session.rx.data(...) in the background.
I would like to have some isRunning observer in my view model which I could subscribe to to know if it's do a network request.
Is it something I could do without making any amendments to my api class?
I'm new in reactive programming so any help would be appreciated.
Thanks.
Here's a solution using a helper class written by RxSwift authors in RxSwift Examples called ActivityIndicator.
The ideas is simple
struct MyViewModel {
/// 1. Create an instance of ActivityIndicator in your viewModel. You can make it private
private let activityIndicator = ActivityIndicator()
/// 2. Make public access to observable part of ActivityIndicator as you already mentioned in your question
var isRunning: Observable<Bool> {
return activityIndicator.asObservable()
}
func getProducts(categoryId: Int) -> Observable<[Product]> {
return api.products(categoryId: categoryId)
.trackActivity(activityIndicator) /// 3. Call trackActivity method in your observable network call
}
}
In related ViewController you can now subscribe to isRunning property. For instance:
viewModel.isLoading.subscribe(onNext: { loading in
print(loading)
}).disposed(by: bag)

Working with Model async data and TableView

I'm creating an app and I have all the logic done, but I want to do a Code refactoring and create MVC pattern. But I dealing with some asynchronous informations, that came from API.
/MenuViewController
Alamofire.request(.GET, Urls.menu).responseJSON { request in
if let json = request.result.value {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let data = JSON(json)
var product: [Product] = []
for (_, subJson): (String, JSON) in data {
product += [Product(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].doubleValue)]
}
dispatch_async(dispatch_get_main_queue()) {
self.products += product
self.tableView.reloadData()
}
}
}
}
This is my code, already working. But I want to create a Model that will handle this and just return the array of Products to my MenuViewController.
Model/Menu
class Menu {
var products: [Product] = []
init() {
Alamofire.request(.GET, Urls.menu).responseJSON { request in
if let json = request.result.value {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let data = JSON(json)
var product: [Product] = []
for (_, subJson): (String, JSON) in data {
product += [Product(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].doubleValue)]
}
dispatch_async(dispatch_get_main_queue()) {
self.products += product
}
}
}
}
}
func totalOfProducts() -> Int {
return self.products.count
}
func getProducts() -> [Product]? {
return self.products
}
func getProductFromIndex(index: Int) -> Product {
return self.products[index]
}
}
But I got my self thinking, how I gonna get the main_queue to another class?
So I tried something like this:
class MenuViewControlvar: UITableViewController {
var products: [Product] = []
let menu: Menu = Menu()
// MARK: View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if let products = menu.getProducts() {
self.tableView.reloadData()
}
// rest of the code
But didn't worked. My TableView is never updated.
I was wondering if I can do this, or I've to keep my Alamofire code in my viewDidLoad() from my MenuViewController
Thank you.
I am just giving you a direction with the step I would follow (Not writing the code thinking you can work it out):
First, write a networking class that accepts network request along with a competition block. Completion block shall be executed as soon as networking is done. This is a wrapper class and can be used across classes.
Second, write a model class that has all the parameters necessary for view controller's functionalities/view drawing.
Third, from view controller, call the networking class. In completion block, pass the model setting, table reload code and any code to remove loading overlay/indicator. This block should get executed on main queue.
Fourth, add code to show loading overlay/indicator before you trigger networking.
Delegation is an ideal solution for this problem of updating your model data and your view based on an asynchronous network call and it’s pretty much the same technique that is implemented throughout the iOS SDK to solve the same problem. There are many benefits of delegation over observation, another viable solution.
First, move your networking code to a separate class
class NetworkingController {
Create a protocol that view controllers can conform to. This provides the loose coupling between your network operations and your views to effectively maintain separation between the MVC layers.
#protocol NetworkingControllerDelegate: class {
func menuDataDidUpdate()
}
Have the networking controller support a property for its delegate
weak var delegate: NetworkingControllerDelegate?
In summary your networking class now looks something like this:
#protocol NetworkingControllerDelegate: class {
func menuDataDidUpdate()
}
class NetworkingController {
weak var delegate: NetworkingControllerDelegate?
// Insert networking functions here.
}
Then, have your view controller conform to this protocol like so
class MenuViewController: NetworkingControllerDelegate {
and create a new network controller in your view controller
var myNetworkController = NetworkController()
and set the delegate of your network controller instance to be your view controller
myNetworkController.delegate = self
Then in your networking code, when the network request has completed and your model has been updated, make a call to the networking controller's delegate.
delegate.menuDidUpdate()
Create the implementation for this method in your view controller since it is now the delegate for your networking code.
func menuDidUpdate() {
// Update your menu.
}
This makes your view controller look something like:
class MenuViewController: NetworkingControllerDelegate {
var myNetworkController = NetworkController()
override func viewDidLoad() {
myNetworkController.delegate = self
}
// MARK: NetworkingControllerDelegate
func menuDidUpdate() {
// Update your menu.
}
}
This is just the outline of the implementation to give you the necessary information about how to proceed. Fully adapting this to your problem is up to you.

ios ViewModel with ReactiveCocoa v3 and Swift 1.2

I'm having trouble using ReactiveCocoa in version 3. I want to build some view model for my login view controller. In my view controller I have outlet for password text field:
#IBOutlet weak var passwordTextField: UITextField!
In view model I have property for the text that is the password
public let emailText = MutableProperty<String>("")
and the question is how to bind it together? I'm able to get SignalProducer from text field:
emailTextField.rac_textSignal().toSignalProducer()
but how to bind it to emailText property? I've read in documentation that SignalProducer is not a Signal, but it can create now. There is method start() but it takes Sink as parameter and I'm a bit confused with design at this moment. Shouldn't emailText be a Sink?
Note: this is not properly an answer to your question, but I think it might help you.
If you are just want to bind your view to your view model, I suggest you to read this post which provides a one-class solution to the problem.
From there, you can very simply implement a 2-way binding so your viewmodel get updated every time the view changes and vice-versa. Here is my extension:
class TwoWayDynamic<T> {
typealias Listener = T -> Void
private var viewListener: Listener?
private var controllerListener: Listener?
private(set) var value: T
func setValueFromController(value: T) {
self.value = value
viewListener?(value)
}
func setValueFromView(value: T) {
self.value = value
controllerListener?(value)
}
func setValue(value: T) {
self.value = value
controllerListener?(value)
viewListener?(value)
}
init(_ v: T) {
value = v
}
func bindView(listener: Listener?) {
self.viewListener = listener
}
func bindController(listener: Listener?) {
self.controllerListener = listener
}
func bindViewAndFire(listener: Listener?) {
self.viewListener = listener
listener?(value)
}
func bindControllerAndFire(listener: Listener?) {
self.controllerListener = listener
listener?(value)
}
}
Hope it helps!

Resources