Haneke / HanekeSwift

A lightweight generic cache for iOS written in Swift with extra love for images.
Apache License 2.0
5.2k stars 591 forks source link

Add possibility to use custom NSURLRequest #197

Open iko3 opened 9 years ago

iko3 commented 9 years ago

Images I'm trying to download are protected and need server authentication to access them. Would be great if it would be possible to respond to authentication challanges or set custom headers (basic64 authorization) when using imageView.hnk_setImageFromURL(...)

Evilcome commented 9 years ago

@iko3 you can create a custom fetcher

import Haneke

public class AppNetworkFetcher<T: DataConvertible> : NetworkFetcher<T> {

    public override var session : NSURLSession {
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.HTTPAdditionalHeaders = [
            "Session-Id": "your_session_id",
            "Client-Version": "your_app_version"
        ];
        return NSURLSession(configuration: configuration)
    }

    public override init(URL : NSURL) {
        super.init(URL: URL)
    }
}

then, use the fetcher:

var cache = Shared.JSONCache
var url = NSURL(string: "http://swift.how")!
var fetcher = AppNetworkFetcher<Haneke.JSON>(URL: url)

cache.fetch(fetcher: fetcher)
.onSuccess { json in
      ...
}
.onFailure { err in
      ...
}

I think you can fetch image in the same way.