Jan R.
Jan R.

Reputation: 223

Response Data via URLSessionUploadTask

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

Upvotes: 4

Views: 3165

Answers (2)

Jan R.
Jan R.

Reputation: 223

I probably found the answer, just add this to URLSession:dataTask:didReceiveResponse:completionHandler: delegate method.

completionHandler(URLSession.ResponseDisposition.allow)

I found solution in this thread.

Upvotes: 4

Raghav7890
Raghav7890

Reputation: 458

try this!, get a NSMutableData as buffer like this globally

fileprivate var buffer:NSMutableData = NSMutableData()

and in your URLSession delegate method add,

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  if let _ = error {
        print(error!.localizedDescription)
    }else {
      // do your parsing with buffer here.
    }
}

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

Upvotes: 2

Related Questions