about SessionDelegate
SessionDelegate 集所有URLSessionDelegate及其子类于一生
包含一下子类功能
basic:
URLSessionDelegate
extend:
URLSessionTaskDelegate
URLSessionDataDelegate
URLSessionDonwloadDelegate
URLSessionStreamDelegate
这样一个SessionDelegate类,就集成了所有session代理功能,不要针对某种具体的session,去初始化相应的URLSessionDelegate子类
Session delegate handle
Alamofire 提供用户多种处理session消息的方法
- SessionDelegate 默认处理
- SessionDelegate userHandleWithCompletion(message)
- SessionDelegate userHandle(message)
- TaskDelegate userHandle(message)
- TaskDelegate 默认处理
那么这么多处理方法,不会冲突吗? 比如一个向左一个向右的问题的情况下如何处理?
看下这个代码就明白了
SessionDelegate file
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task]?.delegate {
delegate.urlSession(
session,
task: task,
didReceive: challenge,
completionHandler: completionHandler
)
} else {
urlSession(session, didReceive: challenge, completionHandler: completionHandler)
}
}
TaskDelegate file
@objc(URLSession:task:didReceiveChallenge:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
那么阅读这段代码优先级很明了了,优先级如下:
- SessionDelegate userHandleWithCompletion(message)
- SessionDelegate userHandle(message)
- TaskDelegate userHandle(message)
- TaskDelegate 默认处理
- SessionDelegate 默认处理
网友评论