Last active
May 6, 2017 08:21
-
-
Save hemant3370/13c4f089620a4190c7a8144cefd7772d to your computer and use it in GitHub Desktop.
image loading and disk saving using alamofire
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ImageExt.swift | |
// Dabbagul | |
// | |
// Created by Hemant Singh on 06/05/17. | |
import Foundation | |
import Alamofire | |
extension UIImageView { | |
var documentsUrl: URL { | |
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! | |
} | |
func setImage(from url: URL, withPlaceholder placeholder: UIImage? = nil) { | |
if let filename = url.absoluteString.components(separatedBy: "/").last { | |
if let img = load(fileName: filename) { | |
DispatchQueue.main.async { | |
self.image = img | |
return | |
} | |
} | |
else{ | |
self.image = placeholder | |
Alamofire.request(url.absoluteString).responseData { (res) in | |
if let data = res.data { | |
let image = UIImage(data: data) | |
if image != nil { | |
// Save image. | |
self.save(image: image!, filename: filename) | |
DispatchQueue.main.async { | |
self.image = image | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
private func save(image: UIImage, filename : String) { | |
let fileURL = documentsUrl.appendingPathComponent(filename) | |
if let imageData = UIImageJPEGRepresentation(image, 1.0) { | |
try? imageData.write(to: fileURL, options: .atomic) | |
} | |
print("Error saving image") | |
} | |
private func load(fileName: String) -> UIImage? { | |
let fileURL = documentsUrl.appendingPathComponent(fileName) | |
do { | |
let imageData = try Data(contentsOf: fileURL) | |
return UIImage(data: imageData) | |
} catch { | |
print("Error loading image : \(error)") | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment