Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Authorization Header field with kingfisher lib

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?

like image 632
sony Avatar asked May 29 '17 07:05

sony


2 Answers

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)
    }
}
like image 112
Eric Aya Avatar answered Nov 06 '22 13:11

Eric Aya


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"))]
}
like image 24
SPatel Avatar answered Nov 06 '22 14:11

SPatel