user6520075
user6520075

Reputation:

How to download image?

Use this code for downloading image. But image doesn’t appear on display.

  NSURL *url = [NSURL URLWithString:
 @"http://upload.wikimedia.org/wikipedia/commons/7/7f/Williams_River-27527.jpg"];

NSURLSessionDownloadTask *downloadPhotoTask = [[NSURLSession sharedSession]
 downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
  _downloadedImage = [UIImage imageWithData:
    [NSData dataWithContentsOfURL:location]];
}];

// 4    
[downloadPhotoTask resume];

_downloadedImage = [UIImage imageNamed:@"Williams_River-27527.jpg"];
    [_book3 setBackgroundImage: _downloadedImage forState:UIControlStateNormal];
    [_scroller addSubview:_book3];

UPD

I update my code in my xcode project but it doesn’t work too… Why it code doesn’t work too in my Xcode project?

#import "ViewController.h"

@interface ViewController () <NSURLSessionDelegate, NSURLSessionDownloadDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:@"http://cdn.tutsplus.com/mobile/uploads/2013/12/sample.jpg"]];
    [downloadTask resume];

}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSData *data = [NSData dataWithContentsOfURL:location];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.progressView setHidden:YES];
        [self.imageView setImage:[UIImage imageWithData:data]];
    });
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {

}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    float progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.progressView setProgress:progress];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

Why it code doesn’t work too in my Xcode project?

Upvotes: 5

Views: 4840

Answers (4)

ypakala
ypakala

Reputation: 1209

Simple and pure answer for Xamarin.iOS:

var url = new NSUrl("https:yourUrl.com");

var task = await NSUrlSession.SharedSession.CreateDataTaskAsync(url);
var image = UIImage.LoadFromData(task.Data);

yourImageView.Image = image;

Upvotes: 0

Pankaj Gaikar
Pankaj Gaikar

Reputation: 2483

Here is answer for Swift

    let url = URL.init(string: "https:yourUrl.com") as! URL

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let error = error {
            print("Error needs to be handled")
            return
        }

        let image = UIImage.init(data: data!)
        DispatchQueue.main.async {
            self.yourImageView.image = image
        }
    }.resume()

Upvotes: 1

ObjectAlchemist
ObjectAlchemist

Reputation: 1127

You create the first instance of an image by loading it from your bundle: _downloadedImage = [UIImage imageNamed:@"Williams_River-27527.jpg"]; (hopefully there is one)

After downloading the image from your url you create a second instance of an image with the downloaded content. But your button still links to the first instance (strong reference). The button simply do not know the new image.

So if you wanna change the displayed image you have to set it again directly after assign it to _downloadedImage:[_book3 setBackgroundImage: _downloadedImage forState:UIControlStateNormal];

Maybe you need to refresh the ui after that.

Upvotes: 0

Putz1103
Putz1103

Reputation: 6211

If you want this to work as the code stands (not sure that it will) then you need to run the steps in this process:

//1     
NSURL *url = [NSURL URLWithString:
  @"http://upload.wikimedia.org/wikipedia/commons/7/7f/Williams_River-27527.jpg"];

// 2    
NSURLSessionDownloadTask *downloadPhotoTask = [[NSURLSession sharedSession]
 downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    // 3 
    _downloadedImage = [UIImage imageWithData:
    [NSData dataWithContentsOfURL:location]];

    //5
    dispatch_async(dispatch_get_main_queue(), ^{
        [_book3 setBackgroundImage: _downloadedImage forState:UIControlStateNormal];
        [_scroller addSubview:_book3];
    });
}];

// 4    
[downloadPhotoTask resume];

Upvotes: 4

Related Questions