我想寫一個使用Swift擴展的委託方法的默認行爲如下,但它永遠不會被調用。有誰知道爲什麼或如何以正確的方式做到這一點?Swift擴展的協議方法的默認實現
extension NSURLSessionDelegate {
public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
//default behaviour here
}
}
添加override
也不起作用。
據this, 蘋果的默認實現是這樣的:
extension NSURLSessionDelegate {
func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { }
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { }
}
我DataTask要求通常是這樣的:
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfiguration.HTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
let session = NSURLSession(configuration: sessionConfiguration)
let requestURL = NSURL(string:"https:www.google.com/blabla")
session.dataTaskWithURL(requestURL!, completionHandler: completion).resume()
凡completion
通常會通過參數收到了斯威夫特關閉。
我需要在整個應用程序中爲所有nsurlsessiontask
實現實現URLSession(... didReceiveChallenge ...)
函數,但無法設置會話的委託,因爲我需要使用completionHandler(正如我在下面的評論中提到的那樣)。
如果你在委託中實現了你的方法,那麼這個方法是否被調用?也許委託方法不會被調用。否則你的實現看起來很好。 –
我用'dataTaskWithURL'和一個completionHandler(我不能通過委託來改變其他原因),所以在創建session時我不能爲我的'NSURLSession'設置一個特定的委託 - else completionHandler isn不叫。另見我更新的問題。 – Stephan