ios – 路由Viper架构

如何在Viper架构的项目中创建良好的路由?我开始创建路由文件,但我不明白我接下来要做什么.

我创建了一个文件线框第一个控制器和线框协议:

//  ChooseLanguageWireframeProtocol.swift

import UIKit

@objc protocol ChooseLanguageWireframeProtocol {
    func presentChooseLanguageViewControllerWindow()
    func presentAuthScreenViewController()
}

在文件线框我添加:

//  ChooseLanguageWireframe.swift

import UIKit

class ChooseLanguageWireframe: NSObject , ChooseLanguageWireframeProtocol{

    var chooseLanguageScreenViewController: ChooseLanguageViewController?
    var window: UIWindow?

    func presentChooseLanguageViewControllerWindow() {
        let chooseLanguageViewController = UIStoryboard.init(name: "ChooseLanguage", bundle: nil).instantiateViewController(withIdentifier: "ChooseLanguage") as? ChooseLanguageViewController
        self.chooseLanguageScreenViewController = chooseLanguageViewController
        self.window!.rootViewController = chooseLanguageScreenViewController
        self.window!.makeKeyAndVisible()
    }
    func presentAuthScreenViewController() {

    }
}

在我创建RootWireframe之后

//  RootWireframe.swift

import UIKit

class RootWireframe: NSObject {

    let chooseLanguageScreenWireframe : ChooseLanguageWireframe?

    override init() {
     //What i must init??
    }

    func application(didFinishLaunchingWithOptions launchOptions: [AnyHashable: Any]?, window: UIWindow) -> Bool  {
        self.chooseLanguageScreenWireframe?.window = window
        return true
    }

}

在AppDelegate文件中我只更改

var window: UIWindow?
    let rootWireframe = RootWireframe()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.rootWireframe.application(didFinishLaunchingWithOptions: launchOptions as [NSObject : AnyObject]?, window: self.window!)
    }

我必须添加或更改正确的工作?

最佳答案 2种可能性:

更改rootViewframe的init以接受您的依赖项并初始化它.
顺便说一下你的变量类型不应该是真正的类型而是协议,所以你可以在测试中轻松地模拟它

let chooseLanguageScreenWireframe : ChooseLanguageWireframeProtocol?

override init(chooseLanguage: ChooseLanguageWireframeProtocol) {
self.chooseLanguageScreenWireframe = chooseLanguage
}

然后在appdelegate中创建chooseLanguageWireframe实现并将其传递给构造函数.
这使得依赖性清晰可见.您也可以删除选项,因为您始终初始化它.

或解决方案2
在appdelegate中创建chooseLanguageWireframe并将其注入构造函数外部

lazy var rootWireframe = {
let r = RootWireframe()
r.chooseLanguageScreenWireframe = self.chooseLanguageScreenWireframe
return r
}

无论如何,您需要在某处实例化您的依赖项,它们无法自动创建.
您通常使用工厂并在依赖注入框架的帮助下执行此操作(检查SwiftInject或Typhoon)

此外,使用协议类型声明所有依赖项,VIPER体系结构的目的是简化测试和模拟与actor之间的隔离

点赞