ios-viper-xcode-templates

ios-viper-xcode-templates

iOS VIPER架构Xcode模板工具包

这个开源项目为iOS开发者提供了一套Xcode模板,用于快速构建VIPER架构的应用。它包含VIPER模块生成器、基类和接口定义,以及使用文档和示例。这些模板有助于实现关注点分离、提高代码可测试性,避免MVC架构的常见问题。项目还支持SwiftUI集成,适合构建易于维护的iOS应用。

iOSVIPER架构模块化Xcode模板Github开源项目

iOS VIPER

Versions

Latest version is v5.0

If you need to use any older version you can find them:

Installation instructions

To install VIPER Xcode templates clone this repo and run the following command from the root folder:

make install_templates

To uninstall Xcode template run:

make uninstall_templates

After that, restart your Xcode if it was already opened.

Demo project

There's a TV Shows demo project in Demo folder. You can find the most common VIPER module use cases in it. If you're already familiar with the base Viper modules you can check out our RxModule Guide.

If you want to check out how you could use Formatter in your apps, feel free to check out Formatter Guide.

SwiftUI hosted module documentation and demo

The 5.0 version includes support for integrating SwiftUI into Viper modules. There's a simple demo project in the Demo folder. The documentation for using SwiftUI hosted modules can be found in Viper x SwiftUI Guide.

VIPER short introduction

How to organize all your code and not end up with a couple of <i>Massive View Controllers</i> with millions of lines of code? In short, VIPER (View Interactor Presenter Entity Router) is an architecture that, among other things, aims at solving the common Massive View Controller problem in iOS apps. When implemented to its full extent it achieves complete separation of concerns between modules, which also yields testability. This is good because another problem with Apple's Model View Controller architecture is poor testability.

If you search the web for VIPER architecture in iOS apps you'll find a number of different implementations and a lot of them are not covered in enough detail. At Infinum we have tried out several approaches to this architecture in real-life projects and with that we have defined our own version of VIPER which we will try to cover in detail here.

Let's go over the basics quickly - the main components of VIPER are as follows:

  • View: contains UI logic and knows how to layout and animate itself. It displays what it's told by the Presenter and it delegates user interaction actions to the Presenter. Ideally, it contains no business logic, only view logic.
  • Interactor: used for fetching data when requested by the Presenter, regardless of where the data is coming from. Contains only business logic.
  • Presenter: also known as the event handler. Handles all the communication with view, interactor, and wireframe. Contains presentation logic - basically it controls the module.
  • Entity: models which are handled by the Interactor. Contains only business logic, but primarily data, not rules.
  • Formatter(new): handles formatting logic. Sits between the presenter and the view. It formats the data from the business world into something that can be consumed by the view.
  • Router: handles navigation logic. In our case, we use components called Wireframes for this responsibility.

Components

Your entire app is made up of multiple modules which you organize in logical groups and use one storyboard for that group. In most cases the modules will represent screens and your module groups will represent user stories, business flows, and so on.

Module components:

  • View
  • Presenter
  • Interactor (not mandatory)
  • Formatter (not mandatory)
  • Wireframe

In some simpler cases, you won't need an Interactor for a certain module, which is why this component is not mandatory. These are cases where you don't need to fetch any data, which is usually not common.

Wireframes inherit from the BaseWireframe. Presenters and Interactors do not inherit any class. Views most often inherit UIViewControllers. All protocols should be located in one file called Interfaces. More on this later.

Communication and references

The following pictures show relationships and communication for one module.

iOS VIPER GRAPH

Let's take a look at the communication logic.

  • LoginViewController communicates with LoginPresenter via a LoginPresenterInterface protocol
  • LoginPresenter communicates with LoginViewController via a LoginViewInterface protocol
  • LoginPresenter communicates with LoginInteractor via a LoginInteractorInterface protocol
  • LoginPresenter communicates with LoginWireframe via a LoginWireframeInterface protocol

The communication between most components of a module is done via protocols to ensure scoping of concerns and testability. Only the Wireframe communicates directly with the Presenter since it actually instantiates the Presenter, Interactor, and View and connects the three via dependency injection.

Now let's take a look at the references logic.

  • LoginPresenter has a strong reference to LoginInteractor
  • LoginPresenter has a strong reference to LoginWireframe
  • LoginPresenter has a unowned reference to LoginViewController
  • LoginViewController has a strong reference to LoginPresenter

The reference types might appear a bit counter-intuitive, but they are organized this way to ensure all module components are not deallocated from memory as long as one of its Views is active. In this way, the Views lifecycle is also the lifecycle of the module - which actually makes perfect sense.

The creation and setup of module components are done in the Wireframe. The creation of a new Wireframe is almost always done in the previous Wireframe. More details on this later in the actual code.

Before we go into detail we should comment on one somewhat unusual decision we made naming-wise and that's suffixing protocol names with "Interface" (LoginWireframeInterface, RegisterViewInterface, ...). A common way to do this would be to omit the "Interface" part but we've found that this makes code somewhat less readable and the logic behind VIPER harder to grasp, especially when starting out.

1. Base classes and interfaces

The module generator tool will generate five files - but for these to work you will need a couple of base protocols and classes. To get them in your project you should create a new file in Xcode and from the template selection screen, under the VIPER Templates section, select BaseInterfaces, and put them in some common folder in your project, perhaps in Common/VIPER. Let's start by covering these base files: WireframeInterface, BaseWireframe, ViewInterface, InteractorInterface, PresenterInterface, UIStoryboardExtension:

WireframeInterface and BaseWireframe

import UIKit protocol WireframeInterface: AnyObject { } class BaseWireframe<ViewController> where ViewController: UIViewController { private weak var _viewController: ViewController? // We need it in order to retain the view controller reference upon first access private var temporaryStoredViewController: ViewController? init(viewController: ViewController) { temporaryStoredViewController = viewController _viewController = viewController } } extension BaseWireframe: WireframeInterface { } extension BaseWireframe { var viewController: ViewController { defer { temporaryStoredViewController = nil } guard let vc = _viewController else { fatalError( """ The `ViewController` instance that the `_viewController` property holds was already deallocated in a previous access to the `viewController` computed property. If you don't store the `ViewController` instance as a strong reference at the call site of the `viewController` computed property, there is no guarantee that the `ViewController` instance won't be deallocated since the `_viewController` property has a weak reference to the `ViewController` instance. For the correct usage of this computed property, make sure to keep a strong reference to the `ViewController` instance that it returns. """ ) } return vc } var navigationController: UINavigationController? { return viewController.navigationController } } extension UIViewController { func presentWireframe<ViewController>(_ wireframe: BaseWireframe<ViewController>, animated: Bool = true, completion: (() -> Void)? = nil) { present(wireframe.viewController, animated: animated, completion: completion) } } extension UINavigationController { func pushWireframe<ViewController>(_ wireframe: BaseWireframe<ViewController>, animated: Bool = true) { pushViewController(wireframe.viewController, animated: animated) } func setRootWireframe<ViewController>(_ wireframe: BaseWireframe<ViewController>, animated: Bool = true) { setViewControllers([wireframe.viewController], animated: animated) } }

The Wireframe is used in 2 steps:

  1. Initialization using a UIViewController (see the init method). Since the Wireframe is in charge of performing the navigation it needs access to the actual UIViewController with which it will do so.
  2. Navigation to a screen (see the pushWireframe, presentWireframe and setRootWireframe methods). Those methods are defined on UIViewController and UINavigationController since those objects are responsible for performing the navigation.

ViewInterface, InteractorInterface, and PresenterInterface

protocol ViewInterface: AnyObject { } extension ViewInterface { }
protocol InteractorInterface: AnyObject { } extension InteractorInterface { }
protocol PresenterInterface: AnyObject { } extension PresenterInterface { }

These interfaces are initially empty. They exist just to make it simple to insert any and all functions needed in all views/interactors/presenters in your project. ViewInterface and InteractorInterface protocols need to be class-bound because the Presenter will hold them via a weak reference.

Ok, let's get to the actual module. First, we'll cover the files you get when creating a new module via the module generator.

2. What you get when generating a module

When running the module generator you will get five files. Say we wanted to create a Home module, we would get the following: HomeInterfaces, HomeWireframe, HomePresenter, HomeView, and HomeInteractor. Let's go over all five.

Interfaces

protocol HomeWireframeInterface: WireframeInterface { } protocol HomeViewInterface: ViewInterface { } protocol HomePresenterInterface: PresenterInterface { } protocol HomeInteractorInterface: InteractorInterface { }

This interface file will provide you with a nice overview of your entire module in one place. Since most components communicate with each other via protocols we found it very useful to put all of these protocols for one module in one place. That way you have a very clean overview of the entire behavior of the module.

Wireframe

final class HomeWireframe: BaseWireframe<HomeViewController> { // MARK: - Private properties - private let storyboard = UIStoryboard(name: "Home", bundle: nil) // MARK: - Module setup - init() { let moduleViewController = storyboard.instantiateViewController(ofType: HomeViewController.self) super.init(viewController: moduleViewController) let interactor = HomeInteractor() let presenter = HomePresenter(view: moduleViewController, interactor: interactor, wireframe: self) moduleViewController.presenter = presenter } } // MARK: - Extensions - extension HomeWireframe: HomeWireframeInterface { }

It generates a Storyboard file for you too so you don't have to create one yourself. You can tailor the Storyboard to match its purpose.

Presenter

final class HomePresenter { // MARK: - Private properties - private unowned let view: HomeViewInterface private let interactor: HomeInteractorInterface private let wireframe: HomeWireframeInterface // MARK: - Lifecycle - init( view: HomeViewInterface, interactor: HomeInteractorInterface, wireframe: HomeWireframeInterface ) { self.view = view self.interactor = interactor self.wireframe = wireframe } } // MARK: - Extensions - extension HomePresenter: HomePresenterInterface { }

This is the skeleton of a Presenter which will get a lot more meat on it once you start implementing the business logic.

View

final class HomeViewController: UIViewController { // MARK: - Public properties - var presenter: HomePresenterInterface! // MARK: - Life cycle - override func viewDidLoad() { super.viewDidLoad() } } // MARK: - Extensions - extension HomeViewController: HomeViewInterface { }

Like the Presenter above, this is only a skeleton that you will populate with IBOutlets, animations and so on.

Interactor

final class HomeInteractor { } extension HomeInteractor: HomeInteractorInterface { }

When generated your Interactor is also a skeleton that you will in most cases use to perform fetching of data from remote API services, Database services, etc.

3. How it really works

Here's an example of a wireframe for a Home screen. Let's start with the Presenter.

final class HomePresenter { // MARK: - Private properties - private unowned let view: HomeViewInterface private let interactor: HomeInteractorInterface private let wireframe: HomeWireframeInterface private var items: [Show] = [] { didSet { view.reloadData() } } // MARK: - Lifecycle - init( view: HomeViewInterface, interactor: HomeInteractorInterface, wireframe: HomeWireframeInterface ) { self.view = view self.interactor = interactor self.wireframe = wireframe } } // MARK: - Extensions - extension HomePresenter: HomePresenterInterface { func logout() { interactor.logout() wireframe.navigateToLogin() } var numberOfItems: Int { items.count } func item(at indexPath: IndexPath) -> Show { items[indexPath.row] } func itemSelected(at indexPath: IndexPath) { let show = items[indexPath.row] wireframe.navigateToShowDetails(id: show.id) } func loadShows() { view.showProgressHUD() interactor.getShows { [unowned self] result in switch result { case .failure(let error): showValidationError(error) case .success(let shows): items = shows } view.hideProgressHUD() } } } private extension HomePresenter { func showValidationError(_ error: Error) { wireframe.showAlert(with: "Error", message: error.localizedDescription) } }

In this simple example, the Presenter fetches TV shows by doing an API call and handles the result. The Presenter can also handle the logout action and item selection in a tableView which is delegated from the view. If an item has been selected the Presenter will initiate the opening of the Details screen.

final class HomeWireframe: BaseWireframe<HomeViewController> { // MARK: - Private properties - private let storyboard = UIStoryboard(name: "Home", bundle: nil) // MARK: - Module setup - init() { let moduleViewController = storyboard.instantiateViewController(ofType: HomeViewController.self) super.init(viewController: moduleViewController) let interactor = HomeInteractor() let presenter = HomePresenter(view: moduleViewController, interactor: interactor, wireframe: self) moduleViewController.presenter = presenter } } // MARK: - Extensions - extension HomeWireframe: HomeWireframeInterface { func navigateToLogin() { navigationController?.setRootWireframe(LoginWireframe()) } func navigateToShowDetails(id: String) { navigationController?.pushWireframe(DetailsWireframe()) } }

This is also a simple example of a wireframe that handles two navigation functions. You've maybe noticed the showAlert Wireframe method used in the Presenter to display alerts. This is used in the BaseWireframe in this concrete project and looks like this:

func showAlert(with title: String?, message: String?) { let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) showAlert(with: title, message: message, actions: [okAction]) }

This is just one example of some shared logic you'll want to put in your base class or maybe one of the base protocols.

Here's an example of a simple Interactor we used in the Demo project:

final class HomeInteractor { private let userService: UserService private let showService: ShowService init(userService: UserService = .shared, showService: ShowService = .shared) { self.userService = userService self.showService = showService } } // MARK: - Extensions - extension HomeInteractor: HomeInteractorInterface { func getShows(_ completion: @escaping ((Result<[Show], Error>) -> ())) { showService.getShows(completion) } func logout() { userService.removeUser() } }

The Interactor contains services that actually communicate with the server. The Interactor can contain as many services as needed but beware that you don't add the ones that aren't needed.

How it's organized in Xcode

Using this architecture impacted the way we organize our projects. In most cases, we have four main subfolders in the project folder: Application, Common, Modules, and Resources. Let's go over those a bit.

Application

Contains AppDelegate and any other app-wide components, initializers, appearance classes, managers and so on. Usually this folder contains only a few files.

Common

Used for all common utility and view components grouped in subfolders. Some common cases for these groups are Analytics, Constants, Extensions, Protocols, Views, Networking, etc. Also here is where we

编辑推荐精选

TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

热门AI工具生产力协作转型TraeAI IDE
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI助手AI工具AI写作工具AI辅助写作蛙蛙写作学术助手办公助手营销助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

聊天机器人AI助手热门AI工具AI对话
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

热门AI工具AI办公办公工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

模型训练热门AI工具内容创作智能问答AI开发讯飞星火大模型多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

AI助手热门AI工具AI创作AI辅助写作讯飞绘文内容运营个性化文章多平台分发
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多