I'm working on building my first App with Swift 3, and I'm having some difficulty hooking into the URLSession Delegate methods. I've been reading over the docs and I believe that I have the correct protocols specified and the appropriate delegate methods defined, but for some reason, the didReceive:data method is not being called at all. What's curious is the delegate method for didReceive:response is firing and giving me the expected content length.
These are the protocols I'm specifying when I define my class:
class DataManager: NSObject, URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegateHere is the creation and calling of my URLSession.dataTask:
let session: URLSession = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
let request: URLRequest = URLRequest(url: requestUrl)
let dataTask: URLSessionDataTask = session.dataTask(with: request)
dataTask.resume()And here are the delegate methods I implented:
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
print("urlSession -> didReceiveResponse")
self.stream.length = 0
self.streamLength = Int(response.expectedContentLength)
print("expectedLength: \(self.streamLength)")
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
print("urlSession -> didReceiveData")
self.stream.append(data)
self.percentDownloaded = Float(self.stream.length) / Float(self.streamLength)
print("percentage: \(self.percentDownloaded)")
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print("urlSession -> didCompleteWithError")
print("\(error?.localizedDescription)")
}Can anyone help me work out what the issue is?
Am I missing something obvious/simple?
Bah, these things can be subtle. I had to actually run your code to spot the error )-:
The problem with your code is that you’re not calling the completion handler that’s passed to
urlSession(_:dataTask:didReceive:completionHandler:). Without that the request just stalls waiting for you to respond.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"