【发布时间】: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