Insert Authorization Header field with kingfisher lib
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 Kingfisherlet 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) }}
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"))]}