首页 > 解决方案 > 无法转换“URL”类型的值?到预期的参数类型“数据”

问题描述

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

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

我修改了 handleSave 函数,使用它调用另一个函数 uploadData(),我从这里 ( 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;
        }
    }
}

标签: swiftamazon-s3aws-amplify

解决方案


你必须DataURL

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

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


推荐阅读