Michael Boiman Michael Boiman - 3 months ago 23
Swift Question

AWSMobileHub Caching Images from S3 in IOS with Swift

I am trying to download an image from S3 to cache it.
This without caching is working:

let manager = AWSUserFileManager.defaultUserFileManager()
let content = manager.contentWithKey("public%2F" + userID + "_profile.jpg")
content.getRemoteFileURLWithCompletionHandler({[weak self](url: NSURL?, error: NSError?) -> Void in
guard let url = url else {
print("Error getting URL for file. \(error)")
return
}
let imageData = NSData(contentsOfURL: url)
imageView.image = UIImage(data: imageData!)
})


And this with caching is not working:

let content = manager.contentWithKey("public%2F" + userID + "_profile.jpg")
if !content.cached {
print("Not Cached")
imageView.image = UIImage(named: "UserIcon")
content.downloadWithDownloadType(AWSContentDownloadType.IfNewerExists, pinOnCompletion: false, progressBlock: nil, completionHandler: { (content: AWSContent?, data: NSData?, error: NSError?) -> Void in
print("Cached")
imageView.image = UIImage(data: data!)
})
} else {
print("Cached2")
imageView.image = UIImage(data: content.cachedData)
}


I get in error after completion: domain: "com.amazonaws.AWSContentManager.ErrorDomain" - code: 1

what is wrong in my code?

Answer

I find it out. It is necessary to use the progress!

 if !content.cached {
        print("Not Cached")
        imageView.image = UIImage(named: "UserIcon")
        content.downloadWithDownloadType(AWSContentDownloadType.IfNewerExists, pinOnCompletion: false, progressBlock: {(content: AWSContent?, progress: NSProgress?) -> Void in
             return
            }, completionHandler: { (content: AWSContent?, data: NSData?, error: NSError?) -> Void in
            if let error = error {
               print("Failed to download a content from a server.)")
                print("Error " + error.debugDescription)
                return
                }
            print("Cached")
            imageView.image = UIImage(data: data!)

        })
    } else {
        print("Cached2")
        imageView.image = UIImage(data: content.cachedData)
    }