//
// ViewController.swift
// TestOnce
//
// Created by point on 2018/5/22.
// Copyright © 2018年 whiteboard. All rights reserved.
//
import UIKit
//
extension UIViewController {
public class func myOnceMethod() {
DispatchQueue.once(token: "ddddddd") {
let originalSelector = Selector.sysP
let swizzledSelector = Selector.sysP2
changeMethod(originalSelector, swizzledSelector, self)
}
}
static func changeMethod(_ original:Selector,_ swizzled:Selector,_ object: AnyClass) -> () {
let originalMethod = class_getInstanceMethod(object, original)
let swizzledMethod = class_getInstanceMethod(object, swizzled)
let didAddMethod: Bool = class_addMethod(object, original, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
if didAddMethod {
class_replaceMethod(object, swizzled, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
}
@objc func DCPresent(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Swift.Void)? = nil) {
print("sssss")
DispatchQueue.main.async {
self.DCPresent(viewControllerToPresent, animated: flag, completion: nil)
}
}
}
fileprivate extension Selector {
// static let viewWillAppear = #selector(UIViewController.viewWillAppear(_:))
// static let yz_viewWillAppear = #selector(UIViewController.yz_viewWillAppear(animated:))
static let sysP = #selector(UIViewController.present(_:animated:completion:))
static let sysP2 = #selector(UIViewController.DCPresent(_:animated:completion:))
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.present(SBViewController(), animated: true, completion: nil)
}
}
extension DispatchQueue {
private static var onceTracker = [String]()
open class func once(token: String, block:() -> Void) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
if onceTracker.contains(token) {
return
}
onceTracker.append(token)
block()
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIViewController.myOnceMethod()
// Override point for customization after application launch.
return true
}