使用翠鸟lib插入授权标题字段

son*_*ony 7 xcode ios sdwebimage kingfisher

我正在使用Kingfisher来显示来自网址的图片,但我的端点需要一个授权标头.如何在iOS中使用Kingfisher或SDWebImage这些网址?

aya*_*aio 9

使用Kingfisher,您需要创建一个请求修饰符(类型AnyModifier)并将其作为参数传递options.kf.setImage方法的一部分,然后使用尾随闭包来实际设置图像.

例:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)


SPa*_*tel 7

集中式可靠的方式传递自定义页眉的所有图片请求。

所有setImage(with:,option :)调用都不需要选项

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
    }
}
Run Code Online (Sandbox Code Playgroud)

设定档

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    KingfisherManager.shared.defaultOptions = [.requestModifier(TokenPlugin(token:"abcdef123456"))]
}
Run Code Online (Sandbox Code Playgroud)