Search code examples
swiftamazon-s3swiftuisdwebimagekingfisher

iOS app: how to use kingfisher/sdwebimage to download aws s3 image


i want to show images from aws s3 protected folder in collectionview or list in my swiftui project using kingfisher. But i couldn't find a solution to show the images as aws requires additional headers to be included in request. I tried adding custom header mentioned in Cheatsheet, but nothing happens.


Solution

  • You can choose what key Kingfisher uses for the cache. So, create a presigned s3 url, then when loading the image use your s3 key as the cache rather then the full presigned url.

                let getPreSignedURLRequest = AWSS3GetPreSignedURLRequest()
                getPreSignedURLRequest.bucket = media.bucket
                getPreSignedURLRequest.key = media.key
                getPreSignedURLRequest.httpMethod = .GET
                getPreSignedURLRequest.expires = Date(timeIntervalSinceNow: 3600)  // Change the value of the expires time interval as required
                AWSS3PreSignedURLBuilder.default().getPreSignedURL(getPreSignedURLRequest).continueWith { (task:AWSTask<NSURL>) -> Any? in
                    if let error = task.error as NSError? {
                        print("Error: \(error)")
                        return nil
                    }
                    if let presignedURL = task.result {
                        DispatchQueue.main.async {
                            self.imageView.kf.indicatorType = .activity
                            let resource = ImageResource(downloadURL: URL(string: presignedURL.absoluteString!)!, cacheKey: media.key)
                            self.imageView.kf.setImage(with: resource)
                        }
                    }
                    return nil
                }