【发布时间】:2016-03-04 21:09:19
【问题描述】:
我正在尝试使用如下的 Swift 扩展为委托方法编写默认行为,但它从未被调用。有谁知道为什么或如何以正确的方式做到这一点?
extension NSURLSessionDelegate {
public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
//default behaviour here
}
}
添加override 也不起作用。
根据this, 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 闭包。
我需要在整个应用程序中为所有nsurlsessiontask 实现实现URLSession(... didReceiveChallenge ...) 函数,但由于我需要使用completionHandler(如下面的评论中所述),因此无法设置我的会话委托。
【问题讨论】:
-
如果你在你的委托中实现你的方法,这个方法是否被调用过?也许委托方法不会被调用。否则你的实现看起来不错。
-
我将
dataTaskWithURL与completionHandler 一起使用(由于其他原因,我无法将其更改为通过委托进行管理),因此在创建时我无法为NSURLSession设置特定委托session - 否则 completionHandler 不会被调用。另请参阅我更新的问题。
标签: ios nsurlsession swift-extensions protocol-extension