I'm using Kingfisher to show image from url, but my endpoint requires a Authorization header. How to use these kind of url with Kingfisher or SDWebImage in iOS?
I'm using Kingfisher to show image from url, but my endpoint requires a Authorization header. How to use these kind of url with Kingfisher or SDWebImage in iOS?
Centralised and reliable way to pass custom headers to all the image requests.
No option required for all setImage(with:,option:) call
class TokenPlugin: ImageDownloadRequestModifier {
let token:String
init(token:String) {
self.token = token
}
func modified(for request: URLRequest) -> URLRequest? {
var request = request
request.addValue(token, forHTTPHeaderField: "token")
return request
}
}
Config
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
KingfisherManager.shared.defaultOptions = [.requestModifier(TokenPlugin(token:"abcdef123456"))]
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let modifier = AnyModifier { request in
var req = request
req.addValue("your_token", forHTTPHeaderField: "authorization")
return req
}
KingfisherManager.shared.defaultOptions += [
.requestModifier(modifier)
]}
Swift 5 + Kingfisher 7.1.2 tested on Xcode 13.2.1
With Kingfisher you need to make a request modifier (of type AnyModifier) and pass it as a parameter in the options part of the .kf.setImage method, and then use the trailing closure to actually set the image.
-> Because I use Firebase, I use getFirebaseToken()
extension UIImageView {
func loadImage(from url: URL, placeHolderImage: UIImage? = nil) {
let modifier = AnyModifier { request in
var r = request
if let firebaseToken = AccountManager.shared.getFirebaseToken() {
r.setValue("Bearer \(firebaseToken)", forHTTPHeaderField: "Authorization")
}
return r
}
self.kf.setImage(with: url, placeholder: placeHolderImage, options: [.requestModifier(modifier), .forceRefresh])
}
}