对'URLSession'使用依赖注入会导致“BAD ACCESS”无限循环错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对'URLSession'使用依赖注入会导致“BAD ACCESS”无限循环错误相关的知识,希望对你有一定的参考价值。

目前我在我的代码中添加了依赖注入,因此可以使用模拟'URLSession'进行单元测试。我用这篇文章作为参考:Guide to network unit testing swift这是代码的样子(减去模拟数据):

// Protocol for MOCK/Real
protocol URLSessionProtocol {
    typealias DataTaskResult = (Data?, URLResponse?, Error?) -> Void

    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol
}

protocol URLSessionDataTaskProtocol {
    func resume()
}

//MARK: HttpClient Implementation
class HttpClient {

    typealias completeClosure = ( _ data: Data?, _ error: Error?)->Void

    private let session: URLSessionProtocol

    init(session: URLSessionProtocol) {
        self.session = session

    }

    func get( url: URL, callback: @escaping completeClosure ) {
        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "GET"
        let task = session.dataTask(with: request) { (data, response, error) in
            callback(data, error)
        }
        task.resume()
    }

}

//MARK: Conform the protocol
extension URLSession: URLSessionProtocol {
    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol

    {
        return dataTask(with: request, completionHandler: completionHandler) as URLSessionDataTaskProtocol

    }
}

extension URLSessionDataTask: URLSessionDataTaskProtocol {}

我首先尝试使用“URLSession.shared”运行它以确保它在真实环境中运行:

let HTTP = HttpClient(session: URLSession.shared)

HTTP.get(url: URL(string: "https://sampleUrl")!) { (data, error) in}

此处出现错误“BAD ACCESS”:

extension URLSession: URLSessionProtocol {
    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol

    {
        return dataTask(with: request, completionHandler: completionHandler) as URLSessionDataTaskProtocol//This is where the error happens

    }
}

我可以在调试导航器中看到URLSession.dataTask(with:completionHandler)一遍又一遍地重复,直到它崩溃。

答案

找到如何解决这个问题,不得不重写Swift4的协议:

protocol URLSessionProtocol {
    func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol
}

以上是关于对'URLSession'使用依赖注入会导致“BAD ACCESS”无限循环错误的主要内容,如果未能解决你的问题,请参考以下文章

URLSession downloadTask 在后台运行时的行为?

完成后在后台下载并唤醒应用程序

Dagger2 User's Guide(翻译)

为啥 URLSession.DataTaskPublisher 从来不发布值?

后台应用刷新对后台 URLSession 有影响吗?

使用Xcodeproj修改依赖库顺序