I need to upload an mp4 video file from iPhone/iPad to a server, also in the background, so I read that is possible with URLSession.uploadTask(with: URLRequest, from
After some attempts, I saw the URLSession.uploadTask(with: URLRequest, fromFile: URL) method attaches the file as raw body to the request, so the problem was the server counterpart that was parsing form-data requests instead raw body requests.After I fixed the server side script, the upload works in background with this code:
var request = URLRequest(url: "my_url")
request.httpMethod = "POST"
request.setValue(file.lastPathComponent, forHTTPHeaderField: "filename")
let sessionConfig = URLSessionConfiguration.background(withIdentifier: "it.example.upload")
sessionConfig.isDiscretionary = false
sessionConfig.networkServiceType = .video
let session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: OperationQueue.main)
let task = session.uploadTask(with: request, fromFile: file)
task.resume()