Response Data via URLSessionUploadTask

Viewed 2484

I am writing simple handler for communication with REST API on server (currently local). Everything goes well so far with downloading and uploading data from/to server.

What I am trying to achieve now is to be able to handle JSON response returned by server after uploading data. This message is something like this:

{"message":"Record successfully added.","recordID":30}

Important is for me the recordID, because I need to assign it to relevant NSManagedObject. I use delegation attitude instead of completionHandler so I would be able to manage progress of the upload. Appropriate delegate class implements these protocols with all methods:

class ConstructoHTTPHelper:NSObject, URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate, URLSessionStreamDelegate { ... }

Here comes the issue because as far as I create upload task with something like this:

let config = URLSessionConfiguration.default 
self.session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main) //URLSession(configuration: config)
var request:URLRequest = URLRequest(url:address)
request.httpMethod = "POST"
let data = // creation of data ...
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("uploadData")
do {
   try data.write(to: fileURL)
}   catch {
   // handling error
}
self.sessionUploadTask = self.session?.uploadTask(with: request, fromFile: fileURL)
self.sessionUploadTask!.resume()

The delegate func for handling data:

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {}

returned by server is never called. What is strange to me is that when I use completion Handler like the one below, It prints the JSON well:

self.sessionUploadTask = self.session?.uploadTask(with: request, from: data, completionHandler: { (data, response, error) in
   print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)
})

So it looks to me that uploadTask is limited in this way. Any suggestions?

Thanks

2 Answers
Related