2

I have a tableView with customCells and I need to load pictures from a REST API (access with auth token). As Im a noob in swift I came across some libraries and it seems KingFisher or AlamofireImage are good ones for asynch loading and caching images retrieved from an API call.

But since my API here has an access token, how can that being passed into this request?

//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) }
        )
    }

For example in Alamofire there is the field headers where the access token can be passed

 //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)
            }
    }

But with AlamofireImage the field headers seems not to be available

//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)")
            }
    }
Stefan Badertscher
  • 331
  • 1
  • 6
  • 20
  • Centralised and reliable way to pass custom headers to all the image requests. Refer this answer https://stackoverflow.com/a/50929243/6630644 – SPatel Jun 19 '18 at 13:13

3 Answers3

4

You could just use the request modifier and pass it as an option to Kingfisher's setting image method. Like this:

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)])

See the wiki page of Kingfisher for more.

onevcat
  • 4,591
  • 1
  • 25
  • 31
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()
Inan
  • 31
  • 4
-1

I figured that out eventually

create the following in 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()
        )

use it in 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")
        }
    }
Stefan Badertscher
  • 331
  • 1
  • 6
  • 20