我遇到错误“ 错误:无法将类型'(Data ?, URLResponse ?, Error?)-> Void'的值转换为预期的参数类型'(Data ?, URLResponse ?, Error?)->写入URLSessionProtocol扩展名时无效'”
protocol URLSessionProtocol {
typealias DataTaskResult = (Data?, URLResponse?, Error?) -> ()
func dataTask(request: URLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTask
}
extension URLSession: URLSessionProtocol {
func dataTask(request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
return dataTask(with: request, completionHandler: completionHandler)
}
}
下面是调用dataTask的类,
final class URLSessionProvider: ProviderProtocol {
private var session: URLSessionProtocol
init(session: URLSessionProtocol = URLSession.shared) {
self.session = session
}
func request(service: ServiceProtocol, completion: @escaping (NetworkResponse) -> ()) {
let request = URLRequest(service: service)
let task = session.dataTask(request: request, completionHandler: { [weak self] data, response, error in
let httpResponse = response as? HTTPURLResponse
self?.handleDataResponse(data: data, response: httpResponse, error: error, completion: completion)
})
task.resume()
}
private func handleDataResponse(data: Data?, response: HTTPURLResponse?, error: Error?, completion: (NetworkResponse) -> ()) {
guard error == nil else {
return completion(.failure(.unknown))
}
guard let response = response else {
return completion(.failure(.noJSONData))
}
switch response.statusCode {
case 200...299:
guard let data = data else { return completion(.failure(.unknown)) }
completion(.success(data: data))
default:
completion(.failure(.unknown))
}
}
}
感谢所有输入来解决问题