无法转换“ URL”类型的值?到预期的参数类型“数据”

时间:2019-05-28 08:18:33

标签: swift amazon-s3 aws-amplify

我正在尝试构建一个录像机应用程序,在录制视频后,我可以将文件上传到AWS S3。我在视频录制应用程序中使用uploadData()函数时遇到问题。

我正在使用camerakit-ios库(https://github.com/CameraKit/camerakit-ios)和aws-amplify ios库。

我通过使用handleSave函数调用另一个函数uploadData()修改了handleSave函数,该函数是我在此处引用的(https://aws-amplify.github.io/docs/ios/storage)。

我的handleSave()函数收到错误Cannot convert value of type 'URL?' to expected argument type 'Data'。我知道这是因为格式错误,但是对于同时使用iOS和AWS S3库我真的很陌生。我应该如何实现呢?

class VideoPreviewViewController: UIViewController {

    ...

    @IBAction func handleSave(_ sender: Any) {
        if let url = self.url {
            uploadData(data: self.url) //ERROR: Cannot convert value of type 'URL?' to expected argument type 'Data'
        }
    }

    func uploadData(data: Data) {

//        let data: Data = Data() // Data to be uploaded

        let expression = AWSS3TransferUtilityUploadExpression()
        expression.progressBlock = {(task, progress) in
            DispatchQueue.main.async(execute: {
                // Do something e.g. Update a progress bar.
            })
        }

        var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
        completionHandler = { (task, error) -> Void in
            DispatchQueue.main.async(execute: {
                // Do something e.g. Alert a user for transfer completion.
                // On failed uploads, `error` contains the error object.
            })
        }

        let transferUtility = AWSS3TransferUtility.default()

        transferUtility.uploadData(data,
                                   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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您必须从Data获得URL

   if let url = self.url,
      let data = try? Data(contentsOf: url) {
         uploadData(data: data)
    }

如果URL是本地的,则此语法是合理的,对于远程URL,您需要异步API。