Я использую Kingfisher для отображения изображения с URL-адреса, но для моей конечной точки требуется заголовок авторизации. Как использовать такие URL-адреса с Kingfisher или SDWebImage в iOS?
Вставьте поле заголовка авторизации с помощью библиотеки kingfisher
Ответы (2)
С 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)
}
}
person
Eric Aya
schedule
04.06.2017
Централизованный и надежный способ передачи настраиваемых заголовков во все запросы изображений.
Опция не требуется для всех вызовов 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"))]
}
person
SPatel
schedule
19.06.2018