无法从AWS S3,Swift 3下载图像

时间:2017-12-26 06:08:13

标签: swift amazon-web-services amazon-s3 swift3

我上传到AWSS3的图片正在尝试使用以下代码下载。

代码不会通过transferManager.download(downloadRequest).continueWith(executor: AWSExecutor.default(), block: { (task: AWSTask<AnyObject>) -> Any? in运行,有人可以建议我如何解决此问题。

使用的AWS开发工具包版本(来自pod文件)   pod 'AWSCore', '~> 2.6.7' pod 'AWSS3', '~> 2.6.7'

static func testDownload(){ 

    let transferManager = AWSS3TransferManager.default()

    let downloadingFileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("temp.jpg")

    if let downloadRequest = AWSS3TransferManagerDownloadRequest(){

        downloadRequest.bucket = "bucket-name"
        downloadRequest.key = "folderName/imageName.png"
        downloadRequest.downloadingFileURL = downloadingFileURL
        print("downloadRequest \(downloadRequest)")
        transferManager.download(downloadRequest).continueWith(executor: AWSExecutor.default(), block: { (task: AWSTask<AnyObject>) -> Any? in

            print("transferManager.download func called")

            if( task.error != nil){
                print(task.error!.localizedDescription)
                return nil
            }

            print(task.result!)

            if let data = NSData(contentsOf: downloadingFileURL){

                DispatchQueue.main.async(execute: { () -> Void in
                    let image = UIImage(data: data as Data)
                    print("Downloaded Image: \(image)")
                })
            }
            return nil
        })
    }
}

1 个答案:

答案 0 :(得分:1)

该块是完成处理程序,将在下载完成后调用。您可以使用以下代码跟踪下载过程的进度:

downloadRequest.downloadProgress = {(bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in
    DispatchQueue.main.async(execute: {() -> Void in
        //Update progress
    })
}

此外,您可以尝试使用主线程进行测试,以查看您的存储桶配置或info.plist值是否有问题。

transferManager.download(downloadRequest).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask<AnyObject>) -> Any? in

    if let error = task.error as? NSError {
        if error.domain == AWSS3TransferManagerErrorDomain, let code = AWSS3TransferManagerErrorType(rawValue: error.code) {
            switch code {
            case .cancelled, .paused:
                break
            default:
                print("Error downloading: \(downloadRequest.key) Error: \(error)")
            }
        } else {
            print("Error downloading: \(downloadRequest.key) Error: \(error)")
        }
        return nil
    }
    print("Download complete for: \(downloadRequest.key)")
    let downloadOutput = task.result
    return nil
})

来源:http://docs.aws.amazon.com/mobile/sdkforios/developerguide/s3transfermanager.html