injectionIII iOS代码注入工具(下)

injectionIII iOS代码注入工具(下)

本文将解决如何使用injectionIII对主页热重载,如果对injectionIII不了解的同学请回到上篇查看

Vaccine

简单地说Vaccine其实是injectionIII的注入功能无法注入的地方通过它来进行实现,从整体上观看Vaccine整个框架的文件结构来看,里面有很多的extension的文件。


Vaccine文件结构

Vaccine可以用Cocoapods或者Carthage,也可以手动导入项目中的Source文件夹。

pod 'Vaccine'
github "zenangst/Vaccine"

Vaccine样例解析

项目中提供了一个样例项目,按照下面的步骤配置即可

  1. Install InjectionIII from the Mac App Store
  2. git clone git@github.com:zenangst/Vaccine.git
  3. Run pod install in Example/VaccineDemo/
  4. Open and run VaccineDemo.xcworkspace
  5. Select the demo project when InjectionIII wants you to select a folder.
  6. Start having fun 🤩

(不会有人看不懂吧)

这里我们在此项目开始解决文章开头提出的问题:对主页热重载。

先展示在AppDelegate中的关键代码:

func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    Injection.load(then: loadApp).add(observer: self, with: #selector(injected(_:)))
    return true
  }

  private func loadApp() {
  //新建HomeVC
  //配置self.window
  }

  private func configureApperance() {
    UINavigationBar.appearance().barStyle = .default
    UINavigationBar.appearance().tintColor = .blue
  }
  
  @objc open func injected(_ notification: Notification) {
    /*
     TODO: Uncomment line 69 to 70 to change the device resolution you want to test with.
     This will also reload the application by invoking `loadApp()` which creates a new main window.
     */

    //screenBounds = UIScreen.device(.iPhoneX(orientation: nil))
    //loadApp()

    /*
     TODO: Uncomment line 76 to 92 to show detail controller on each injection.
     Animations are temporarely disabled for a better debugging environment.
     */

//    guard let flowController = flowController,
//      let listController = listViewController else { return }
//
//    let contact = Contact(firstName: "John",
//                          lastName: "Appleseed",
//                          phoneNumbers: [
//                            "(888) 555-5512",
//                            "(888) 555-1212"],
//                          emails: ["John-Appleseed@mac.com"],
//                          notes: "Some notes"
//    )
//
//    UIView.setAnimationsEnabled(false)
//    flowController.listViewController(listController, didSelect: contact)
//    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
//      UIView.setAnimationsEnabled(true)
//    }
  }
}

样例中,Vaccine在didFinishLaunchingWithOptions中实现了InjectionIII的注入和添加响应热更新的观察者,另外会调用loadApp方法,也就是我们日常需要实现的homeVCself.window


每当摁下cmd+s,appdelegate作为观察者将会调用injected:方法,如果想重新刷新homeVC,你只需要把self.windowhomeVC重新生成就好了,也就是把loadAPP()的注释解开。

求打赏


posted @ 2020-05-16 15:45  MrYu4  阅读(94)  评论(0编辑  收藏  举报