How to block url in swift?

I followed this tutorial to drown URLSession. An example was performed by creating a protocol and extending an existing one URLSession.

protocol URLSessionProtocol {
    typealias DataTaskResult = (Data?, URLResponse?, Error?) -> Void
    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol
}

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

Unit tests work as expected. But when I try to run the real thing, URLSession -> datatask () gets into an infinite loop and crashes. It seems that datatask () is calling itself.

What am I missing, please?

UPDATE:

protocol URLSessionDataTaskProtocol {
    var originalRequest: URLRequest? { get }
    func resume()
}

extension URLSessionDataTask: URLSessionDataTaskProtocol {}
+4
source share
1 answer

I finally found a solution. It's amazing when we missed the forest behind the trees. There are two questions:

1) Swift 4 seems to have changed the signature dataTask(with: NSURLRequest)todataTask(with: URLRequest)

funct , dataTask URLSession, , . , NSURLRequest URLRequest .

2) , dataTask cast URLSessionDataTask, .

Swift 4:

typealias DataTaskResult = (Data?, URLResponse?, Error?) -> Void

protocol URLSessionProtocol {
    func dataTask(with request: URLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol
}

extension URLSession: URLSessionProtocol {
    func dataTask(with request: URLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol {
        let task:URLSessionDataTask = dataTask(with: request, completionHandler: {
            (data:Data?, response:URLResponse?, error:Error?) in completionHandler(data,response,error) }) as URLSessionDataTask
        return task
    }
}

, URLSession.shared , URLSession(), .

0

Source: https://habr.com/ru/post/1695402/


All Articles