我正在使用 Kingfisher 显示来自 url 的图像,但我的端点需要一个 Authorization 标头。如何在 iOS 中将此类 url 与 Kingfisher 或 SDWebImage 一起使用?
问问题
4419 次
3 回答
20
使用 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)
}
}
于 2017-06-04T11:53:12.163 回答
15
将自定义标头传递给所有图像请求的集中且可靠的方法。
所有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
}
}
配置
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
KingfisherManager.shared.defaultOptions = [.requestModifier(TokenPlugin(token:"abcdef123456"))]
}
于 2018-06-19T13:05:58.577 回答
-1
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 在 Xcode 13.2.1 上测试
于 2022-02-18T12:35:26.530 回答