Created
September 4, 2017 17:25
-
-
Save inorganik/488e4cdd7e1636ced9c60df2d3771fb7 to your computer and use it in GitHub Desktop.
returns image data by fetching locally or remote, caching the result so subsequent fetches are local
This file contains 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
func getImageDataWithUrlString(imageUrlString: String) -> NSData? { | |
let url = URL(string: imageUrlString) | |
if let filename: String = url?.lastPathComponent { | |
let imagesDirUrl = try! FileManager.default.url(for: .cachesDirectory, in: .localDomainMask, appropriateFor: nil, create: true) | |
let fileUrl = imagesDirUrl.appendingPathComponent(filename) | |
do { | |
// get a cached copy | |
let _ = try fileUrl.checkResourceIsReachable() | |
let imageData = NSData(contentsOf: fileUrl) | |
return imageData | |
} | |
catch { | |
// need to download | |
let imageData = NSData(contentsOf: url!) | |
imageData?.write(to: fileUrl, atomically: true) | |
return imageData | |
} | |
} | |
else { | |
print("error getting last path component") | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment