2

I have a URL image on the server. I use this to save avatar. How to I can use URL to download image and set in my ImageView.

2 Answers2

9

try to use this code to download image in background

Make sure your url contains a image and it is valid url

NSString *strImgURLAsString = @"imageURL";
[strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *imgURL = [NSURL URLWithString:strImgURLAsString];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (!connectionError) {
        UIImage *img = [[UIImage alloc] initWithData:data];
        // pass the img to your imageview
    }else{
        NSLog(@"%@",connectionError);
    }
}];
Malav Soni
  • 2,739
  • 1
  • 23
  • 52
1

You can try this code

NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];
Vijay yadav
  • 1,220
  • 8
  • 17