我正在尝试使用如下的 Swift 扩展为委托方法编写默认行为,但它从未被调用。有谁知道为什么或如何以正确的方式做到这一点?
extension NSURLSessionDelegate {
public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
//default behaviour here
}
}
添加override
也不起作用。
据此,Apple 的默认实现如下所示:
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
通常是通过参数接收的 Swift 闭包。
我需要为整个应用程序URLSession(... didReceiveChallenge ...)
中的所有实现实现该功能nsurlsessiontask
,但由于我需要使用 completionHandler(如下面的评论中所述),因此无法设置我的会话委托。