2017-05-01 46 views
1

我想調整URLSession類方法dataTask,但無法完成。如何在Swift中swizzle URLSession類方法dataTask 3

我試過這個在objective-c中混合使用,它的工作正常,現在我想在swift 3中實現這個,但沒有得到任何東西。

我指 this鏈接,但它不是在迅速3.

工作請幫助我。

+1

你想通過交叉混合的方法來實現呢?你正在編寫測試用例,想要替換URL調用還是隻是調試? –

回答

1

我們可以調配的迅速方法如下

let selectorfirst = #selector(ClassName.function(_:)) 
let swizzledFunction = #selector(ClassName.function2(_:)) 

let method1 = class_getInstanceMethod(ClassInstance, selectorfirst) 
let method2 = class_getInstanceMethod(ClassInstance, swizzledFunction) 

method_exchangeImplementations(method1, method2) 

//嘗試這樣使用子類

 class URLSessionSubClass: URLSession { 
static var sharedInstance: URLSessionSubClass? 
static func getSharedInstance() -> URLSessionSubClass { 
    if sharedInstance == nil { 
     sharedInstance = URLSessionSubClass() 
     let selectorfirst = #selector(URLSessionSubClass.function(_:)) 
     let swizzledFunction = #selector(URLSessionSubClass.function2(_:)) 

     let method1 = class_getInstanceMethod(self, selectorfirst) 
     let method2 = class_getInstanceMethod(self, swizzledFunction) 

     method_exchangeImplementations(method1, method2) 
    } 
    return sharedInstance! 
} 
} 
+0

請使用URLSession的擴展提供解決方案。 –

相關問題