iOS - How to upload a video with uploadTask?

后端 未结 3 522
Happy的楠姐
Happy的楠姐 2021-01-16 06:52

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

3条回答
  •  半阙折子戏
    2021-01-16 07:32

    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()
    

提交回复
热议问题