Swift创建本地文件,附加其他本地文件以与NSURLSession.uploadTask一起使用

时间:2016-10-18 14:11:01

标签: ios swift nsurlsession nsfilemanager nsurlsessionuploadtask

我正在使用一个API,它接受使用多部分表单数据的视频上传。我想使用NSURLSession.uploadTask(加上它的委托)来处理上传。

我的问题是我需要更改本地视频文件以使用我正在使用的API,我已经创建了一个我想要做的例子:

let localVideoURL = URL(string: "file://AGoodURL/video.mov")!
let apiURL = URL(string: "https://myServer.com/upload")

func uploadVideo() {

let config = URLSessionConfiguration.background(withIdentifier: "myUploads")
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)

var request = NSMutableURLRequest(url: apiURL!)
request.httpMethod = "POST"

// create a new file from the local file + required api data

var boundary : String {

    return "Boundary-\(UUID().uuidString)"
}

// what should be a new file and not an in memory data object, but how?
var data = Data()

// do I need to set these or will the uploadTaskWithFile class handle it?
data.append("--\(boundary)\r\n".data(using: .utf8)!)

data.append("Content-Disposition: form-data; name=\"video\"; filename=\"video.mov\"\r\n".data(using: .utf8)!)

// same question? does this need to be here?
data.append("Content-Type: video/quicktime\r\n\r\n".data(using: .utf8)!)

/** somehow get the data from the local url without loading it into memory */
// data.append(try! Data(contentsOf: localVideoURL)) /** not like this! */

data.append("\r\n".data(using: .utf8)!)
data.append("--\(boundary)--\r\n".data(using: .utf8)!)

// close the new file
// begin an uploadTask with the new file, use URLSessionDelegates.

session.uploadTask(with: request, fromFile: )

}

如何创建新的本地文件,如上所述添加字符串数据,附加本地视频文件并添加其余的字符串数据?这些文件可能非常大,因此将其全部保存在磁盘上非常重要。

1 个答案:

答案 0 :(得分:0)

解决方案是使用输入&使用新的本地临时文件输出流,在创建输出流之后,我附加多部分表单上载所需的标题数据,然后将现有本地文件追加到块中,然后附加结束数据(喜欢边界)并关闭流。

然后我使用该文件,该文件使用NSURLSession uploadTask w / file封装请求的httpBody属性。

相关问题