【问题标题】:How to save Amazon S3 files locally with Swift?如何使用 Swift 在本地保存 Amazon S3 文件?
【发布时间】:2016-07-02 00:51:58
【问题描述】:

我最近一直致力于通过 Amazon S3 服务上传和下载文件的项目,特别是用户上传的个人资料图片。我也在使用 Amazon Cognito(用户名、全名等),我喜欢 Cognito 的一件事是它可以将下载的数据保存在手机本地,即使应用程序离线也能显示出来。然后,当应用程序上线时,它会更新任何数据更改。不幸的是,同样的情况不会发生在 S3 上。每次应用程序启动时,它都必须从我的 S3 存储桶中下载个人资料图片,然后才能显示它们。我想要做的是让应用程序从 iOS 设备上的 S3 存储桶中保存用户的个人资料图片,这样即使应用程序离线,用户也可以看到他们的图片。这是我目前拥有的:

func downloadImage(){

    var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?

    //downloading image
    let S3BucketName: String = "*******"
    let S3DownloadKeyName: String = self.credentialsProvider.identityId + "/profileImage.png"

    let expression = AWSS3TransferUtilityDownloadExpression()
    expression.downloadProgress = {(task: AWSS3TransferUtilityTask, bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) in
        dispatch_async(dispatch_get_main_queue(), {
            let progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
            //   self.statusLabel.text = "Downloading..."
            NSLog("Progress is: %f",progress)
        })
    }

    completionHandler = { (task, location, data, error) -> Void in
        dispatch_async(dispatch_get_main_queue(), {
            if ((error) != nil){
                NSLog("Failed with error")
                NSLog("Error: %@",error!);
                //self.statusLabel.text = "Failed"
            } else {
                //self.statusLabel.text = "Success"
                self.userProfile.image = UIImage(data: data!)
                self.profileBackground.image = UIImage(data: data!)
            }
        })
    }

    let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()

    transferUtility.downloadToURL(nil, bucket: S3BucketName, key: S3DownloadKeyName, expression: expression, completionHander: completionHandler).continueWithBlock { (task) -> AnyObject! in
        if let error = task.error {
            NSLog("Error: %@",error.localizedDescription);
            //  self.statusLabel.text = "Failed"
        }
        if let exception = task.exception {
            NSLog("Exception: %@",exception.description);
            //  self.statusLabel.text = "Failed"
        }
        if let _ = task.result {
            //    self.statusLabel.text = "Starting Download"
            NSLog("Download Starting!")
            // Do something with uploadTask.
        }
        return nil;
    }

} 

提前致谢!

【问题讨论】:

  • 这真的很有用,谢谢!但是,如果一个用户要注销而另一个用户要登录怎么办?照片在更新之前是否仍会短暂显示,还是仍会显示我的占位符图像?再次感谢您的帮助。
  • 所以在注销时,您想清除应用程序数据路径中的所有内容。所以基本上删除了所有图片所在的本地文件夹。
  • 如果您需要帮助使用 AWS stackoverflow.com/questions/35136637/… 登录系统,请查看此链接

标签: ios swift amazon-web-services amazon-s3 amazon-cognito


【解决方案1】:

这是从 S3 Bucket 下载图像并将其保存到本地手机的助手 下次如果您寻求此图像。助手将检查是否存在本地副本,否则将从 S3 下载

import UIKit
import AWSCore
import AWSS3

class S3Helper: NSObject {

@objc var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?

@objc lazy var transferUtility = {
    AWSS3TransferUtility.default()
}()

let DocDirPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

func downloadImage(imageView: UIImageView!, S3Folder: String, S3FileName: String) {
    let S3DownloadKeyName: String = S3Folder + "/" + S3FileName
    imageView.image = UIImage(named: "ic_place_holder.pdf")

    let filePath = DocDirPath.appendingPathComponent(S3FileName).path
    let fileManager = FileManager.default
    if fileManager.fileExists(atPath: filePath) {
        let imageURL = self.DocDirPath.appendingPathComponent(S3FileName)
        imageView.image = UIImage(contentsOfFile: imageURL.path)!
    } else {

        let expression = AWSS3TransferUtilityDownloadExpression()
        expression.progressBlock = {(task, progress) in
            DispatchQueue.main.async(execute: {

            })
        }

        self.completionHandler = { (task, location, data, error) -> Void in
            DispatchQueue.main.async(execute: {
                if let error = error {
                    NSLog("Failed with error: \(error)")
                    //self.statusLabel.text = "Failed"
                }
                else{
                    //self.statusLabel.text = "Success"
                    imageView.image = UIImage(data: data!)

                    do{
                        let imgPath = URL(fileURLWithPath: self.DocDirPath.appendingPathComponent(S3FileName).path)
                        try (imageView.image ?? UIImage(named: "ic_place_holder.pdf")!).jpegData(compressionQuality: 1.0)?.write(to: imgPath, options: .atomic)
                    } catch let error1{
                        print(error1.localizedDescription)
                    }
                }
            })
        }

        transferUtility.downloadData(
            forKey: S3DownloadKeyName,
            expression: expression,
            completionHandler: completionHandler).continueWith { (task) -> AnyObject? in
                if let error = task.error {
                    NSLog("Error: %@",error.localizedDescription);
                    DispatchQueue.main.async(execute: {
                        //self.statusLabel.text = "Failed"
                    })
                }

                if let _ = task.result {
                    DispatchQueue.main.async(execute: {
                        //self.statusLabel.text = "Downloading..."
                    })
                    NSLog("Download Starting!")
                    // Do something with uploadTask.
                }
                return nil;
            }
    }
}

}

【讨论】:

    猜你喜欢
    • 2013-11-26
    • 2011-12-19
    • 2017-10-08
    • 1970-01-01
    • 2015-04-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    相关资源
    最近更新 更多