我有一个带有customCells的tableView,我需要从REST API加载图片(使用auth令牌访问)。 由于我是一个快速的菜鸟,我遇到了一些库,看起来KingFisher或AlamofireImage对于异步加载和缓存从API调用中检索的图像来说是很好的。
但由于我的API在这里有一个访问令牌,如何将其传递给此请求?
//image handling with kingfisher
if let imgView = cell.schoolCoverImage {
imgView.kf_setImageWithURL(
NSURL(string: "")!,
placeholderImage: nil,
optionsInfo: nil,
progressBlock: nil,
completionHandler: { (image, error, CacheType, imageURL) -> () in
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) }
)
}
例如,在Alamofire中,存在可以传递访问令牌的字段标题
//Sample API call with Alamofire
Alamofire.request(
.GET,
baseURL+schools+nonAcademicParameter,
headers: accessToken
)
.responseJSON { response in
switch response.result {
case .Success(let value):
completionHandler(value, nil)
case .Failure(let error):
completionHandler(nil, error)
}
}
但是使用AlamofireImage时,字段标题似乎不可用
//Image request with AlamofireImage
Alamofire.request(
.GET,
"https://httpbin.org/image/png"),
headers: ["Authorization" : "Bearer fbzi5u0f5kyajdcxrlnhl3zwl1t2wqaor"] //not available
.responseImage { response in
debugPrint(response)
print(response.request)
print(response.response)
debugPrint(response.result)
if let image = response.result.value {
print("image downloaded: \(image)")
}
}
答案 0 :(得分:2)
您可以使用请求修饰符并将其作为选项传递给Kingfisher的设置图像方法。像这样:
let modifier = AnyModifier { request in
var r = request
r.setValue("Bearer fbzi5u0f5kyajdcxrlnhl3zwl1t2wqaor", forHTTPHeaderField: "Authorization")
return r
}
imageView.kf.setImage(with: url, placeholder: nil, options: [.requestModifier(modifier)])
有关详情,请参阅Kingfisher的wiki page。
答案 1 :(得分:0)
我最终想到了
在viewdidload()
中创建以下内容//create custom session with auth header
let sessionConfig =
NSURLSessionConfiguration.defaultSessionConfiguration()
let xHTTPAdditionalHeaders: [String : String] =
self.restApi.accessToken
sessionConfig.HTTPAdditionalHeaders = xHTTPAdditionalHeaders
self.imageDownloader = ImageDownloader(
configuration: sessionConfig,
downloadPrioritization: .FIFO,
maximumActiveDownloads: 4,
imageCache: AutoPurgingImageCache()
)
在cellforrowatindexpath中使用它:
let URLRequest = NSURLRequest(URL: NSURL(string: "https:/xxx.com/olweb/api/v1/schools/"+schoolIdString+"/image/"+ImageNameString)!)
self.imageDownloader.downloadImage(URLRequest: URLRequest) { response in
print(response.request)
print(response.response)
debugPrint(response.result)
if let image = response.result.value {
print("here comes the printed image:: ")
print(image)
print(schoolIdString)
cell.schoolCoverImage.image = image
cell.schoolBiggerImage.image = image
} else {
print("image not downloaded")
}
}
答案 2 :(得分:0)
import Foundation
var semaphore = DispatchSemaphore (value: 0)
var request = URLRequest(url: URL(string: "<your url>")!,timeoutInterval: Double.infinity)
request.addValue("Bearer <your token>", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()``
}
task.resume()
semaphore.wait()