快速将多个文件并行上传到 AWS S3,并在表视图单元格中显示进度视图状态



我是 AWS 的新手,我已经使用 TransferUtility 文件转换将一些文件上传到 AWS S3。这是我的方案步骤

1.从iCloud中选择文件

public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
let fileurl: URL = url as URL
let filename = url.lastPathComponent
let file-extension = url.pathExtension
let filedata = url.dataRepresentation
// Call upload function
upload(file: fileurl, keyname: filename, exten: file-extension)
// Append names into array
items.append(item(title: filename, size: string))
self.tableView_util.reloadData()

2. 使用传输实用程序将该文件上传到 AWS S3

private func upload(file url: URL, keyname : String, exten: String) {
transferUtility.uploadfile(file ur,
bucket: "YourBucket",
key: "YourFileName",
contentType: "text/plain",
expression: expression,
completionHandler: completionHandler).continueWith {
(task) -> AnyObject! in
if let error = task.error {
print("Error: (error.localizedDescription)")
}
if let _ = task.result {
// Do something with uploadTask.
}
return nil;
}

3.上传时需要将每个文件上传状态显示在表格视图单元格中

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellutil", for: indexPath) as! UtilityTableViewCell
let item = items[indexPath.row]
}

我的问题:表格视图我可以显示上传项目,但当我上传下一个项目时,第一次上传停止了。我需要实现并行上传多个文件并显示在单元格状态上。

为此,您需要创建一个操作队列,每个上传文件在操作内部写入网络请求并将这些操作添加到队列中。

在这里,我暗示要这样做。

创建具有类似属性的模型类

struct UploadRecordData { 
let fileName:String
let unique_id:String
let progress:double
//...etc
}

然后像这样的操作子类

struct UploadRecordOperation:Operation{
let uploadRecordData:UploadRecordData
//etc..
//update progess inside of operation class
func updateProgress(progress:Double){
uploadRecordData.progress = progress
//edited answer
let myDict = [ "progress": progress, "unique_id":unique_id]
NSNotificationCenter.defaultCenter().postNotificationName("refreshProgressBar", object:myDict);
}
}

现在这里是表视图控制器的一部分

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath)
let row = indexPath.row
let uploadRecordData = uploadfilesRecords[row]
//edited answer  
cell.progressView.uniqud_id = uploadRecord.unique_id
cell.progressView.progress = uploadRecord.progress
return cell
}

这是在更新刷新上传文件进度时刷新单元格的方法。

进度视图的子类如下所示

struct ProgressView:YourProgressView{
var unique_id:int
//Now add notification observer to your progress view
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressView), name: "refreshProgressBar", object: nil)

func refreshProgressView(notification: NSNotification){
let dict = notification.object as! NSDictionary
let progress = dict["progress"]
let u_id = dict["unique_id"]
if u_id == self.unique_id {
self.progress = progress
}
}

请参阅上面更新的代码 操作子类 和表视图委托方法.

最新更新