我有一个带有customCells的tableView,我需要从REST API加载图片(使用auth token访问)。由于我是swift的新手,我偶然发现了一些库,似乎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)")
}
}发布于 2016-10-18 12:48:46
您只需使用request修饰符,并将其作为选项传递给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)])更多信息请参见翠鸟的wiki page。
发布于 2020-01-29 00:10:08
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()发布于 2016-07-20 14:00:11
我最终弄明白了
在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")
}
}https://stackoverflow.com/questions/38464862
复制相似问题