Insert Authorization Header field with kingfisher

2019-05-01 10:06发布

问题:

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?

回答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.

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)
    }
}


回答2:

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"))]
}