I am trying to upload a video / image file using- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;
method using m
To prevent wasting time dealing with it.
The complete snippet based on @dgatwood answer
private func http(request: URLRequest){
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: .main)
/*Tweaking*/
let task = session.uploadTask(with: request, from: request.httpBody!)
task.resume()
}
And.. do not forget to add the Headers on request object like
request.setValue("multipart/form-data; boundary=\(yourboundary)", forHTTPHeaderField: "Content-Type")
You aren't uploading what you think you are. Your intent is for the body data to be uploaded as-is. Instead, when you call uploadTaskWithRequest:fromFile:
, that method effectively nils out any HTTPBody
or HTTPBodyStream
values in the request and replaces them with the contents of the URL that you passed in via the fromFile:
parameter.
So unless you're writing that block of form-encoded body data to that file URL somewhere else, you're uploading the file by itself instead of the multipart form data.
You need to tweak your code to write the form data out to a file instead of storing it in HTTPBody
, then pass the URL of that file to the fromFile:
parameter.