Search code examples
iosswiftswift2nsurlsessionuploadtask

Get server response from NSURLSessionUploadTask using custom delegate


I would like to upload an image to a server by using NSURLSessionUploadTask, which I have already accomplished by using a custom delegate

let task =  NSURLSession(
    configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
    delegate: self,
    delegateQueue: NSOperationQueue.mainQueue()
).uploadTaskWithRequest(request, fromData: data)

task!.resume()

But I am unable to get the server's response. Using task.response returns the error code and other header information, but does not return the actual html shown on the page.

I can't create the url task with a completion handler, because I need to get the progress of the upload.

How can I get the NSData from a page response using NSURLSessionUploadTask?


Solution

  • You can gather the data via didReceiveData, and could have a global NSData instance and append the received data.

    Then, in didCompleteWithError, you can convert the received data to a string to get the response HTML.