分配自定义 URLSessionDelegate 是否会覆盖未实现的方法的默认行为?
Does assigning a custom URLSessionDelegate override default behavior for methods that are not implemented?
在 URLSessionDelegate
的文档中说:
Your URLSession object doesn’t need to have a delegate. If no delegate
is assigned, a system-provided delegate is used, and you must provide
a completion callback to obtain the data.
我只需要实现如下方法之一:
class SessionDelegate: NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
var request = request
request.httpMethod = task.originalRequest?.httpMethod ?? request.httpMethod
completionHandler(request)
}
}
然后像这样初始化我的会话:
self.session = URLSession(configuration: config, delegate: SessionDelegate(), delegateQueue: nil)
对于我没有实现的方法,这会覆盖 "system-provided delegate" 中的任何其他行为吗?
您在 SessionDelegate
class 中未覆盖的任何(可选)函数将遵循原始函数的默认实现行为。
为了检查每个函数的默认行为,请参阅头文件中的文档(选项+单击 URLSessionTaskDelegate)或此处:
https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate
在 URLSessionDelegate
的文档中说:
Your URLSession object doesn’t need to have a delegate. If no delegate is assigned, a system-provided delegate is used, and you must provide a completion callback to obtain the data.
我只需要实现如下方法之一:
class SessionDelegate: NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
var request = request
request.httpMethod = task.originalRequest?.httpMethod ?? request.httpMethod
completionHandler(request)
}
}
然后像这样初始化我的会话:
self.session = URLSession(configuration: config, delegate: SessionDelegate(), delegateQueue: nil)
对于我没有实现的方法,这会覆盖 "system-provided delegate" 中的任何其他行为吗?
您在 SessionDelegate
class 中未覆盖的任何(可选)函数将遵循原始函数的默认实现行为。
为了检查每个函数的默认行为,请参阅头文件中的文档(选项+单击 URLSessionTaskDelegate)或此处:
https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate