Skip to content

Instantly share code, notes, and snippets.

@inorganik
Created September 4, 2017 17:25
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 inorganik/488e4cdd7e1636ced9c60df2d3771fb7 to your computer and use it in GitHub Desktop.
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
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