Skip to content

Instantly share code, notes, and snippets.

@MugunthKumar
Created September 17, 2019 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MugunthKumar/b45cb5909acd499aa34988ef6bb7f6e9 to your computer and use it in GitHub Desktop.
Save MugunthKumar/b45cb5909acd499aa34988ef6bb7f6e9 to your computer and use it in GitHub Desktop.
//
// Created by Mugunth Kumar, Copyright © 2019 MK. All rights reserved.
//
import Foundation
import UIKit
import ImageIO
public extension UIImageView {
func loadImage(url: URL?) -> URLSessionDataTask? {
guard let url = url else { return nil }
let task = URLSession.shared.dataTask(with: url) { [weak self] (imageData, response, error) in
if let imageData = imageData {
// perform image decompression so that our scrolling is butter smooth even with plenty of hi-res images
guard let source = CGImageSourceCreateWithData(imageData as CFData, nil) else { return }
guard let cgImage = CGImageSourceCreateImageAtIndex(source, 0, // cache the decompressed image
[(kCGImageSourceShouldCache as String): false] as CFDictionary?) else { return }
DispatchQueue.main.async {
guard let superview = self?.superview else { return }
UIView.transition(with: superview, duration: 0.45, options: [.allowUserInteraction, .transitionCrossDissolve], animations: {
self?.image = UIImage(cgImage: cgImage, scale: UIScreen.main.scale, orientation: .up)
}, completion: nil)
}
} else {
if let error = error {
print ("URL Fetch Failed with error: \(error)")
}
}
}
task.resume()
return task
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment