import ObjectiveC
import UIKit
private func swizzle(_ vc: UIViewController.Type) {
[
(#selector(vc.viewWillAppear(_:)), #selector(vc.hoge_viewWillAppear(_:)))
]
.forEach { original, swizzled in
guard let originalMethod = class_getInstanceMethod(vc, original),
let swizzledMethod = class_getInstanceMethod(vc, swizzled) else { return }
let didAddViewDidLoadMethod = class_addMethod(
vc,
original,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod)
)
if didAddViewDidLoadMethod {
class_replaceMethod(
vc,
swizzled,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod)
)
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
private var hasSwizzled = false
extension UIViewController {
public final class func doBadSwizzleStuff() {
guard !hasSwizzled else { return }
hasSwizzled = true
swizzle(self)
}
@objc internal func hoge_viewWillAppear(_ animated: Bool) {
self.hoge_viewWillAppear(animated)
let instanceType = type(of: self)
let name = String(reflecting: instanceType)
print(name)
}
}