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?
Asked
Active
Viewed 6,037 times
4 Answers
20
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.
Example:
import Kingfisher
let modifier = AnyModifier { request in
var r = request
// replace "Access-Token" with the field name you need, it's just an example
r.setValue(<YOUR_TOKEN>, forHTTPHeaderField: "Access-Token")
return r
}
let url = URL(string: <YOUR_URL>)
let iView = <YOUR_IMAGEVIEW>
iView.kf.setImage(with: url, options: [.requestModifier(modifier)]) { (image, error, type, url) in
if error == nil && image != nil {
// here the downloaded image is cached, now you need to set it to the imageView
DispatchQueue.main.async {
iView.image = image
}
} else {
// handle the failure
print(error)
}
}

Eric Aya
- 69,473
- 35
- 181
- 253
16
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"))]
}

SPatel
- 4,768
- 4
- 32
- 51
0
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

Alper Öztürk
- 79
- 1
- 4
0
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])
}
}

Milan Savaliya M
- 258
- 3
- 5