Skip to content

Instantly share code, notes, and snippets.

@randhirraj3130
Last active April 12, 2017 13:13
Show Gist options
  • Save randhirraj3130/b307572433ea0729511abdf1a19bfdef to your computer and use it in GitHub Desktop.
Save randhirraj3130/b307572433ea0729511abdf1a19bfdef to your computer and use it in GitHub Desktop.
how to download images from the url and show in your image view in swift 3.0 and objective c
// swift code 3.0
func downloadImage(url: URL)
{
print("Download Started \(url)")
getDataFromUrl(url: url) { (data, response, error) in
guard let data = data, error == nil else { return }
//print(response?.suggestedFilename)
print(url.lastPathComponent)
if(url.lastPathComponent != "safe_image.php"){
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
if let image = UIImage(data: data){
let image1 : ImageClass = ImageClass(image: image)
self.Images.add(image1)
self.ImageView.reloadData()
}else{
print("No Image")
}
}
}
}
}
func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
completion(data, response, error)
}.resume()
}
// objective c code
-(void)DownloadImage:(NSString*)imageUrl{
NSURL *url = [NSURL URLWithString:imageUrl];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSLog(@"Downloading started...");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"dwnld_image.png"];
NSLog(@"FILE : %@",filePath);
[urlData writeToFile:filePath atomically:YES];
UIImage *image1=[UIImage imageWithContentsOfFile:filePath];
self.user_Image.image = image1;
NSLog(@"Completed...");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment