在项目开发后期,要添加友盟统计事件,在阅读友盟相关文档后了解.
友盟统计中要求在每个界面的viewWillAppear和viewWillDisappear方法中添加友盟统计方法:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
MobClick.beginLogPageView("pageName")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
MobClick.endLogPageView("pageName")
}
由于每个界面都要添加这个方法太过于繁琐,因此找个一个更好的办法来添加,通过借助运行时来进行解决:
extension UIViewController {
class func loadBySwift() {
var m1: Method?
var m2: Method?
// 运行时替换方法
m1 =
class_getInstanceMethod(self,
#selector(statisticsViewWillAppear(_:)))
m2 =
class_getInstanceMethod(self,
#selector(viewWillAppear(_:)))
method_exchangeImplementations(m1!, m2!)
m1 =
class_getInstanceMethod(self,
#selector(statisticsViewWillDisappear(_:)))
m2 =
class_getInstanceMethod(self,
#selector(viewWillDisappear(_:)))
method_exchangeImplementations(m1!, m2!)
}
@objc func statisticsViewWillAppear(_ animated: Bool) {
self.statisticsViewWillAppear(animated)
MobClick.beginLogPageView(String(describing: type(of: self)))
}
@objc func statisticsViewWillDisappear(_ animated: Bool) {
self.statisticsViewWillDisappear(animated)
MobClick.endLogPageView(String(describing: type(of: self)))
}
}
在UIViewController拓展类里添加这个方法,在运行时,viewWillAppear方法会被statisticsViewWillAppear替换,viewWillDisappear会被statisticsViewWillDisappear替换,而且每个界面的viewWillAppear和viewWillDisappear方法仍然有效.
方法封装好了,接下来是调用了,通过响应者链的传递方式,决定再拓展UIApplication这个类库:
extension UIApplication {
private static let classSwizzedMethodRunOnce: Void = {
UIViewController.loadBySwift()
}()
open override var next: UIResponder? {
UIApplication.classSwizzedMethodRunOnce
return super.next
}
}
这样就不需要每个界面里都要进行调用了.
由于最近在用Swift做项目,所以方法都是用Swift语法写的,后期有时间会整理一套OC的方法出来.