I want to make sure I'm implementing URLSessionTaskDelegate and URLSessionDataDelegate in correct way. I use them, because I want to be able to track the progress. This is the code so far:
final public fileprivate(set) var data: Data?
final public fileprivate(set) var response: URLResponse?
final public fileprivate(set) var error: Error?
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
if let response = response as? HTTPURLResponse, response.statusCode == 200 {
data = Data()
}
self.response = response
completionHandler(.allow)
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.data?.append(data)
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
self.error = error
// ... Work with downloaded data
}
and a few questions:
If the status code is not 200, often the body of the response includes information that helps you diagnose why it was not 200, so you probably want to continue to capture that information. I'd probably move that status code checking to didCompleteWithError.
I generally expect 200 and thus only check for 200. Technically, all of the 2xx codes are "success" codes, so you might want to consider all of them successful. That's up to you.
The didCompleteWithError is the only connection related error. Theoretically, you might want to check urlSession(_:didBecomeInvalidWithError:). Also, you might want to assign your own error code if you get a non-2xx status code or, at a higher level, if the parsing of the response failed.
They don't appear to have defined an appropriate constant from Swift 3. FYI, looking at the headers, you can see the value is -1, but often we just check for response.expectedContentLength < 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With