2

我有一个带有 customCells 的 tableView,我需要从 REST API 加载图片(使用身份验证令牌访问)。由于我是 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)")
            }
    }
4

3 回答 3

4

您可以只使用请求修饰符并将其作为选项传递给 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 页面

于 2016-10-18T04:48:46.357 回答
1
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()
于 2020-01-28T16:10:08.267 回答
-1

我最终想通了

在 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")
        }
    }
于 2016-07-20T06:00:10.507 回答