Skip to content

Instantly share code, notes, and snippets.

@m25lazi
Created September 16, 2018 13:53
Show Gist options
  • Save m25lazi/83e7d73e43f7826bb2519e185154100c to your computer and use it in GitHub Desktop.
Save m25lazi/83e7d73e43f7826bb2519e185154100c to your computer and use it in GitHub Desktop.
/// Injecting fetcher to the fetch API, so that we get control of downloading outside of the User class
func fetchProfileImage(fetcher: ImageDownloader, then completion: @escaping (Bool)-> Void) {
fetcher.fetch { (image, error) in
if let fetchError = error {
print("Failed to fetch Image with error - \(fetchError)")
completion(false)
} else if let fetchedImage = image {
print("Image fetched")
self.iProfileImage = fetchedImage
completion(true)
} else {
print("Failed to fetch Image with unknown error")
completion(false)
}
}
}
// And you can use it like this
let currentUser = User(name: "Tim Cook")
let imageFetcher = ImageDownloader(url: URL(string: "https://somerandomapp.mlaz.im/images/GkdhaKGjhgj7yjHo")!)
currentUser.fetchProfileImage(fetcher: imageFetcher) { (downloaded) in
if downloaded {
print("Yay!! Show it somewhere!")
} else {
print("Ooops! Failed to download you image!")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment