在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:infinum/iOS-VIPER-Xcode-Templates开源软件地址:https://github.com/infinum/iOS-VIPER-Xcode-Templates开源编程语言:HTML 58.7%开源软件介绍:VersionsLatest version is v4.0. If you need to use any older version you can find them: Installation instructionsTo install VIPER Xcode templates clone this repo and run the following command from root folder:
To uninstall Xcode template run:
After that, restart your Xcode if it was already opened. Demo projectThere's a TV Shows demo project in Demo folder. You can find 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. VIPER short introductionHow to organize all your code and not end up with a couple of Massive View Controllers with millions of lines of code? In short, VIPER (View Interactor Presenter Entity Router) is an architecture which, 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:
ComponentsYour 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:
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 referencesThe following pictures shows relationships and communication for one module. Let's take a look at the communication logic.
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.
The reference types might appear a bit counter-intuitive, but they are organized this way to assure 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 is 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 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 interfacesThe module generator tool will generate five files - but in order for these to work you will need a couple of base protocols and classes. These are also available in the repo. Let's start by covering these base files: WireframeInterface, BaseWireframe, ViewInterface, InteractorInterface, PresenterInterface, UIStoryboardExtension: WireframeInterface and BaseWireframeprotocol WireframeInterface: AnyObject {
}
class BaseWireframe {
private unowned var _viewController: UIViewController
// We need it in order to retain the view controller reference upon first access
private var temporaryStoredViewController: ViewController?
init(viewController: UIViewController) {
temporaryStoredViewController = viewController
_viewController = viewController
}
}
extension BaseWireframe: WireframeInterface {
}
extension BaseWireframe {
var viewController: UIViewController {
defer { temporaryStoredViewController = nil }
return _viewController
}
var navigationController: UINavigationController? {
return viewController.navigationController
}
}
extension UIViewController {
func presentWireframe(_ wireframe: BaseWireframe, animated: Bool = true, completion: (()->())? = nil) {
present(wireframe.viewController, animated: animated, completion: completion)
}
}
extension UINavigationController {
func pushWireframe(_ wireframe: BaseWireframe, animated: Bool = true) {
self.pushViewController(wireframe.viewController, animated: animated)
}
func setRootWireframe(_ wireframe: BaseWireframe, animated: Bool = true) {
self.setViewControllers([wireframe.viewController], animated: animated)
}
}
extension BaseWireframe: WireframeInterface {
} The Wireframe is used in 2 steps:
ViewInterface, InteractorInterface and PresenterInterfaceprotocol ViewInterface: AnyObject {
}
extension ViewInterface {
} protocol InteractorInterface: AnyObject {
}
extension InteractorInterface {
} protocol PresenterInterface: AnyObject {
}
extension PresenterInterface {
} These interfaces are initially empty. They exists just to make it simple to insert any and all functions needed in all views/interactors/presenters in you 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 moduleWhen 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. Interfacesprotocol 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 at one place. Since most components communicate with each other via protocols we found 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. Wireframefinal 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. Presenterfinal 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. Viewfinal 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 which you will populate with IBOutlets, animations and so on. Interactorfinal class HomeInteractor {
}
extension HomeInteractor: HomeInteractorInterface {
} When generated your Interactor is also a skeleton which you will in most cases use to perform fetching of data from remote API services, Database services, etc. 3. How it really worksHere'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 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 which 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 which actually communicate with the server. The Interactor can contain as many services as needed but beware that you don't add the ones which aren't needed. How it's organized in XcodeUsing 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. ApplicationContains AppDelegate and any other app-wide components, initializers, appearance classes, managers and so on. Usually this folder contains only a few files. CommonUsed for all common utility and view components grouped in sub folders. Some common cases for these groups are Analytics, Constants, Extensions, Protocols, Views, Networking, etc. Also here is where we always have a VIPER subfolder which contains the base VIPER protocols and classes. ResourcesThis folder should contain image assets, fonts, audio and video files, and so on. We use one .xcassets for images and in that folder separate images into logical folders so we don't get a long list of files in one place. ModulesAs described earlier you can think of one VIPER module as one screen. In the Modules folder we organize screens into logical groups which are basically user-stories. Each group is organized in a sub-folder which contains one storyboard (containing all screens for that group) and multiple module sub-folders. Useful links
Contributing and developmentFeedback and code contributions are very much welcome. Just make a pull request with a short description of your changes. Before creating a PR, please run:
from By making contributions to this project you give permission for your code to be used under the same license. CreditsMaintained and sponsored by Infinum. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论