Skip to content

Instantly share code, notes, and snippets.

@sanketfirodiya
Created July 14, 2016 07:23
Show Gist options
  • Save sanketfirodiya/a49a7527f94c6a36c699cbcf975facb0 to your computer and use it in GitHub Desktop.
Save sanketfirodiya/a49a7527f94c6a36c699cbcf975facb0 to your computer and use it in GitHub Desktop.
ImageProvider
//
// ImageProvider.swift
// Tuity-iOS
//
// Created by Sanket Firodiya on 7/13/16.
// Copyright © 2016 Tuity. All rights reserved.
//
import UIKit
class ImageProvider: NSObject {
static var sharedInstance = ImageProvider()
private var imageCache = [String: UIImage]()
func fetchImageWithUrl(url: String!, completionBlock: (image: UIImage) -> ()) {
if let image = self.imageCache[url] {
completionBlock(image: image)
} else {
let imageURL = kBaseUrl + "/" + url
let request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
var httpHeaderParams: [String: String] = [:]
httpHeaderParams = NetworkRequest.appendAppIdApiKeyHTTPHeaders(httpHeaderParams)
request.allHTTPHeaderFields = httpHeaderParams
let downloadTask = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
if error == nil {
if let image = UIImage(data: data!) {
dispatch_async(dispatch_get_main_queue(), {
if self.imageCache.indexForKey(url) == nil {
self.imageCache[url] = image
}
completionBlock(image: image)
})
}
}
}
downloadTask.resume()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment