HomeiOS DevelopmentVIPER finest practices for iOS builders

VIPER finest practices for iOS builders


On this tutorial I’ll present you an entire information about find out how to construct a VIPER based mostly iOS software, written completely in Swift.

VIPER

This publish is just a little bit outdated, please anticipate a brand new model coming quickly…

Getting began with VIPER

To begin with, it’s best to learn my earlier (extra theoretical) article concerning the VIPER structure itself. It is a fairly first rate writing explaining all of the VIPER elements and reminiscence administration. I’ve additionally polished it just a little bit, final week. ⭐️

The issue with that article nevertheless was that I have not present you the true deal, aka. the Swift code for implementing VIPER. Now after a full 12 months of tasks utilizing this structure I can lastly share all my finest practices with you.

So, let’s begin by making a model new Xcode undertaking, use the only view app template, identify the undertaking (VIPER finest practices), use Swift and now you are able to take the subsequent step of constructing an superior “enterprise grade” iOS app.


Producing VIPER modules

Lesson 1: by no means create a module by hand, all the time use a code generator, as a result of it is a repetative activity, it is fuckin’ boring plus it’s best to give attention to extra essential issues than making boilerplate code. You should utilize my light-weight module generator referred to as:

VIPERA

Simply obtain or clone the repository from github. You’ll be able to set up the binary device by working swift run set up --with-templates. This can set up the vipera app underneath /usr/native/bin/ and the fundamental templates underneath the ~/.vipera listing. You should utilize your personal templates too, however for now I am going to work with the default one. 🔨

I normally begin with a module referred to as Important that is the foundation view of the appliance. You’ll be able to generate it by calling vipera Important within the undertaking listing, so the generator can use the correct undertaking identify for the header feedback contained in the template information.

Clear up the undertaking construction just a little bit, by making use of my conventions for Xcode, which means sources goes to an Property folder, and all of the Swift information into the Sources listing. These days I additionally change the AppDelegate.swift file, and I make a separate extension for the UIApplicationDelegate protocol.

Create a Modules group (with a bodily folder too) underneath the Sources listing and transfer the newly generated Important module underneath that group. Now repair the undertaking points, by choosing the Information.plist file from the Property folder for the present goal. Additionally do take away the Important Interface, and after that you would be able to safely delete the Important.storyboard and the ViewController.swift information, as a result of we’re not going to wish them in any respect.

Contained in the AppDelegate.swift file, it’s a must to set the Important module’s view controller as the foundation view controller, so it ought to look considerably like this:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder {

    var window: UIWindow?
}

extension AppDelegate: UIApplicationDelegate {

    func software(_ software: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        self.window = UIWindow(body: UIScreen.predominant.bounds)
        self.window?.rootViewController = MainModule().buildDefault()
        self.window?.makeKeyAndVisible()

        return true
    }
}

Congratulations, you’ve got created your very first VIPER module! 🎉


UITabBarController & VIPER

I’ve a brilliant easy resolution for utilizing a tab bar controller in a VIPER module. First let’s generate just a few new modules, these are going to be the tabs. I’ll use the JSONPlaceholder service, so lets say a separate tab for every of those sources: posts, albums, pictures, todos (with the identical module identify). Generate all of them, and transfer them into the modules folder.

Now, let’s generate another module referred to as Residence. This can implement our tab bar controller view. If you’d like you should utilize the Important module for this objective, however I wish to preserve that for animation functions, to have a neat transition between the loading display and my Residence module (all of it is dependent upon your wants).

So the principle logic that we will implement is that this: the principle view will notify the presenter concerning the viewDidAppear occasion, and the presenter will ask the router to show the Residence module. The Residence module’s view will probably be a subclass of a UITabBarController, it will additionally notify it is presenter about viewDidLoad, and the presenter will ask for the correct tabs, by utilizing its router.

Right here is the code, with out the interfaces:

class MainDefaultView: UIViewController {

    var presenter: MainPresenter?

    override func viewDidAppear(_ animated: Bool) {
        tremendous.viewDidAppear(animated)

        self.presenter?.viewDidAppear()
    }
}

extension MainDefaultPresenter: MainPresenter {

    func viewDidAppear() {
        self.router?.showHome()
    }
}

extension MainDefaultRouter: MainRouter {

    func showHome() {
        let viewController = HomeModule().buildDefault()
        self.viewController?.current(viewController, animated: true, completion: nil)
    }
}


extension HomeDefaultView: HomeView {

    func show(_ viewControllers: [UIViewController]) {
        self.viewControllers = viewControllers
    }
}



extension HomeDefaultPresenter: HomePresenter {

    func setupViewControllers() {
        guard let controllers = self.router?.getViewControllers() else {
            return
        }
        self.view?.show(controllers)
    }

}

extension HomeDefaultRouter: HomeRouter {

    func getViewControllers() -> [UIViewController] {
        return [
            PostsModule().buildDefault(),
            AlbumsModule().buildDefault(),
            PhotosModule().buildDefault(),
            TodosModule().buildDefault(),
        ].map { UINavigationController(rootViewController: $0) }
    }
}

class HomeModule {

    func buildDefault() -> UIViewController {
        

        presenter.setupViewControllers()

        return view
    }
}

There may be one further line contained in the Residence module builder operate that triggers the presenter to setup correct view controllers. That is simply because the UITabBarController viewDidLoad technique will get referred to as earlier than the init course of finishes. This behaviour is sort of undocumented however I assume it is an UIKit hack as a way to keep the view references (or only a easy bug… is anybody from Apple right here?). 😊

Anyway, now you may have a correct tab bar contained in the undertaking built-in as a VIPER module. It is time to get some information from the server and right here comes one other essential lesson: not every thing is a VIPER module.


Providers and entities

As you may seen there isn’t a such factor as an Entity inside my modules. I normally wrap APIs, CoreData and plenty of extra information suppliers as a service. This manner, all of the associated entities may be abstracted away, so the service may be simply changed (with a mock for instance) and all my interactors can use the service by way of the protocol definition with out understanding the underlying implementation.

One other factor is that I all the time use my promise library if I’ve to take care of async code. The explanation behind it’s fairly easy: it is far more elegant than utilizing callbacks and non-compulsory consequence components. You must be taught guarantees too. So right here is a few a part of my service implementation across the JSONPlaceholder API:

protocol Api {

    func posts() -> Promise<[Post]>
    func feedback(for publish: Put up) -> Promise<[Comment]>
    func albums() -> Promise<[Album]>
    func pictures(for album: Album) -> Promise<[Photo]>
    func todos() -> Promise<[Todo]>
}



struct Put up: Codable {

    let id: Int
    let title: String
    let physique: String
}



class JSONPlaceholderService {

    var baseUrl = URL(string: "https://jsonplaceholder.typicode.com/")!

    enum Error: LocalizedError {
        case invalidStatusCode
        case emptyData
    }

    personal func request<T>(path: String) -> Promise<T> the place T: Decodable {
        let promise = Promise<T>()
        let url = baseUrl.appendingPathComponent(path)
        print(url)
        URLSession.shared.dataTask(with: url) { information, response, error in
            if let error = error {
                promise.reject(error)
                return
            }
            guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
                promise.reject(Error.invalidStatusCode)
                return
            }
            guard let information = information else {
                promise.reject(Error.emptyData)
                return
            }
            do {
                let mannequin = strive JSONDecoder().decode(T.self, from: information)
                promise.fulfill(mannequin)
            }
            catch {
                promise.reject(error)
            }
        }.resume()
        return promise
    }
}

extension JSONPlaceholderService: Api {

    func posts() -> Promise<[Post]> {
        return self.request(path: "posts")
    }

    
}

Often I’ve a mock service implementation subsequent to this one, so I can simply take a look at out every thing I need. How do I change between these companies? Nicely, there’s a shared (singleton – do not hate me it is utterly effective 🤪) App class that I take advantage of principally for styling functions, however I additionally put the dependency injection (DI) associated code there too. This manner I can cross round correct service objects for the VIPER modules.

class App {

    static let shared = App()

    personal init() {

    }

    var apiService: Api {
        return JSONPlaceholderService()
    }
}



class PostsModule {

    func buildDefault() -> UIViewController {
        let view = PostsDefaultView()
        let interactor = PostsDefaultInteractor(apiService: App.shared.apiService)

        

        return view
    }
}



class PostsDefaultInteractor {

    weak var presenter: PostsPresenter?

    var apiService: Api

    init(apiService: Api) {
        self.apiService = apiService
    }
}

extension PostsDefaultInteractor: PostsInteractor {

    func posts() -> Promise<[Post]> {
        return self.apiService.posts()
    }

}

You are able to do this in a 100 different methods, however I presently want this method. This manner interactors can straight name the service with some additional particulars, like filters, order, type, and so forth. Mainly the service is only a excessive idea wrapper across the endpoint, and the interactor is creating the fine-tuned (higher) API for the presenter.


Making guarantees

Implementing the enterprise logic is the duty of the presenter. I all the time use guarantees so a fundamental presenter implementation that solely hundreds some content material asynchronously and shows the outcomes or the error (plus a loading indicator) is only a few traces lengthy. I am all the time attempting to implement the three fundamental UI stack components (loading, information, error) by utilizing the identical protocol naming conventions on the view. 😉

On the view facet I am utilizing my good previous assortment view logic, which considerably reduces the quantity of code I’ve to put in writing. You’ll be able to go together with the normal method, implementing just a few information supply & delegate technique for a desk or assortment view isn’t a lot code in spite of everything. Right here is my view instance:

extension PostsDefaultPresenter: PostsPresenter {

    func viewDidLoad() {
        self.view?.displayLoading()
        self.interactor?.posts()
        .onSuccess(queue: .predominant) { posts  in
            self.view?.show(posts)
        }
        .onFailure(queue: .predominant) { error in
            self.view?.show(error)
        }
    }
}



class PostsDefaultView: CollectionViewController {

    var presenter: PostsPresenter?

    init() {
        tremendous.init(nibName: nil, bundle: nil)

        self.title = "Posts"
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been applied")
    }

    override func viewDidLoad() {
        tremendous.viewDidLoad()

        self.presenter?.viewDidLoad()
    }
}

extension PostsDefaultView: PostsView {

    func displayLoading() {
        print("loading...")
    }

    func show(_ posts: [Post]) {
        let grid = Grid(columns: 1, margin: UIEdgeInsets(all: 8))

        self.supply = CollectionViewSource(grid: grid, sections: [
            CollectionViewSection(items: posts.map { PostViewModel($0) })
        ])
        self.collectionView.reloadData()
    }

    func show(_ error: Error) {
        print(error.localizedDescription)
    }
}

The cell and the ViewModel is outdoors the VIPER module, I are inclined to dedicate an App folder for the customized software particular views, extensions, view fashions, and so forth.

class PostCell: CollectionViewCell {

    @IBOutlet weak var textLabel: UILabel!
}


class PostViewModel: CollectionViewViewModel<PostCell, Put up> {

    override func config(cell: PostCell, information: Put up, indexPath: IndexPath, grid: Grid) {
        cell.textLabel.textual content = information.title
    }

    override func dimension(information: Put up, indexPath: IndexPath, grid: Grid, view: UIView) -> CGSize {
        let width = grid.width(for: view, gadgets: grid.columns)
        return CGSize(width: width, peak: 64)
    }
}

Nothing particular, if you would like to know extra about this assortment view structure, it’s best to learn my different tutorial about mastering assortment views.


Module communication

One other essential lesson is to discover ways to talk between two VIPER modules. Usually I am going with easy variables – and delegates if I’ve to ship again some kind of information to the unique module – that I cross round contained in the construct strategies. I’ll present you a extremely easy instance for this too.

class PostsDefaultRouter {

    weak var presenter: PostsPresenter?
    weak var viewController: UIViewController?
}

extension PostsDefaultRouter: PostsRouter {

    func showComments(for publish: Put up) {
        let viewController = PostDetailsModule().buildDefault(with: publish, delegate: self)
        self.viewController?.present(viewController, sender: nil)
    }
}

extension PostsDefaultRouter: PostDetailsModuleDelegate {

    func toggleBookmark(for publish: Put up) {
        self.presenter?.toggleBookmark(for: publish)
    }
}




protocol PostDetailsModuleDelegate: class {
    func toggleBookmark(for publish: Put up)
}

class PostDetailsModule {

    func buildDefault(with publish: Put up, delegate: PostDetailsModuleDelegate? = nil) -> UIViewController {
        let view = PostDetailsDefaultView()
        let interactor = PostDetailsDefaultInteractor(apiService: App.shared.apiService,
                                                      bookmarkService: App.shared.bookmarkService)
        let presenter = PostDetailsDefaultPresenter(publish: publish)

        

        return view
    }
}

class PostDetailsDefaultRouter {

    weak var presenter: PostDetailsPresenter?
    weak var viewController: UIViewController?
    weak var delegate: PostDetailsModuleDelegate?
}

extension PostDetailsDefaultRouter: PostDetailsRouter {

    func toggleBookmark(for publish: Put up) {
        self.delegate?.toggleBookmark(for: publish)
    }
}


class PostDetailsDefaultPresenter {

    var router: PostDetailsRouter?
    var interactor: PostDetailsInteractor?
    weak var view: PostDetailsView?

    let publish: Put up

    init(publish: Put up) {
        self.publish = publish
    }
}

extension PostDetailsDefaultPresenter: PostDetailsPresenter {

    func reload() {
        self.view?.setup(with: self.interactor!.bookmark(for: self.publish))

        
        self.interactor?.feedback(for: self.publish)
        .onSuccess(queue: .predominant) { feedback in
            self.view?.show(feedback)
        }
        .onFailure(queue: .predominant) { error in
            
        }
    }

    func toggleBookmark() {
        self.router?.toggleBookmark(for: self.publish)
        self.view?.setup(with: self.interactor!.bookmark(for: self.publish))
    }
}

Within the builder technique I can entry each part of the VIPER module so I can merely cross across the variable to the designated place (identical applies for the delegate parameter). I normally set enter variables on the presenter and delegates on the router.

It is normally a presenter who wants information from the unique module, and I wish to retailer the delegate on the router, as a result of if the navigation sample modifications I haven’t got to alter the presenter in any respect. That is only a private choice, however I like the best way it seems to be like in code. It is actually arduous to put in writing down this stuff in a single article, so I would suggest to obtain my completed pattern code from github.


Abstract

As you possibly can see I am utilizing varied design patterns on this VIPER structure tutorial. Some say that there isn’t a silver bullet, however I consider that I’ve discovered a extremely superb methodology that I can activate my benefit to construct high quality apps in a short while.

Combining Guarantees, MVVM with assortment views on prime of a VIPER construction merely places each single piece into the correct place. Overengineered? Perhaps. For me it is definitely worth the overhead. What do you concentrate on it? Be at liberty to message me by way of twitter. You can too subscribe to my month-to-month publication under.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments