Skip to content

Instantly share code, notes, and snippets.

View chriswebb09's full-sized avatar

Christopher Webb chriswebb09

View GitHub Profile
let imageCache = NSCache<NSString, UIImage>()
func downloadImage(url: URL, completion: @escaping (UIImage?) -> Void)
if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) {
completion(cachedImage, nil)
}
static func downloadImage(url: URL, completion: @escaping (_ image: UIImage?, _ error: Error? ) -> Void) {
if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) {
completion(cachedImage, nil)
} else {
MTAPIClient.downloadData(url: url) { data, response, error in
if let error = error {
completion(nil, error)
} else if let data = data, let image = UIImage(data: data) {
imageCache.setObject(image, forKey: url.absoluteString as NSString)
let url = URL(string: "http://www.google.com")
var defaultSession = URLSession(configuration: .default)
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var downloadProgressLabel: UILabel!
final class iTunesAPIClient: NSObject {
// Network stuff
}
extension iTunesAPIClient: URLSessionDelegate {
internal func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
// Calls background session completion in AppDelegate
}
internal func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64,totalBytesExpectedToWrite: Int64) {
// Gives you the URLSessionDownloadTask that is being executed
// along with the total file length - totalBytesExpectedToWrite
// and the current amount of data that has received up to this point - totalBytesWritten
}
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
// Background completion called here.
}