我想写一个使用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