1

Recently I was doing a project in swift and had to download images from a website over the network, I remember in Objective-C I could do something like this to achieve async downloads and then update the main UI:

- (void)loadImage:(NSString *)stringUrl completion:(void (^)(UIImage *image))completion {

    [[[NSOperationQueue alloc] init] addOperationWithBlock:^{

        NSURL *url = [NSURL URLWithString:stringUrl];

        NSData *data = [NSData dataWithContentsOfURL:url];

        UIImage *image = [UIImage imageWithData:data];

        [[NSOperationQueue mainQueue] addOperationWithBlock:^{

            completion(image);
        }];
    }];
}

And here is what I have so far in Swift:

public func loadImage(completion: @escaping (UIImage) -> Void) { 

        DispatchQueue.global().async {

            do {

                if let url = URL(string: self.url) {

                    let imageData =  try Data(contentsOf: url)

                    if let myImage = UIImage(data: imageData) {

                        DispatchQueue.main.async {

                            completion(myImage)

                        }
                    }
                }
            }
            catch {
                print("error loading image: \(error)")
            }
        }
    }

I am curious as to whether or not the swift version is more or less doing the same thing as I think it is. Mainly should I be using the .sync() or .async() methods on globals() and main()?

Asleepace
  • 3,466
  • 2
  • 23
  • 36
  • Suggestion: scratch all that stuff and start again with URLSession. – Eric Aya May 16 '17 at 17:11
  • @EricAya why should he start with URLSession when it's about simple image downloading? – user3581248 May 16 '17 at 17:19
  • 1
    @user3581248 Because although NSData works it's not the proper way to do it. Using URLSession you have access to the data, the error, the server response, you can do many things... Whereas with NSData you can do only downloading and hope it works well, without possibility of controlling anything. – Eric Aya May 16 '17 at 17:20
  • @EricAya why are you so sure that he even wants to handle the error in this case? Maybe this feature should be failing silently? – user3581248 May 16 '17 at 17:23
  • In this case I'm more curious about the asynchronous operations rather than the mode of downloading if that makes sense – Asleepace May 16 '17 at 17:24
  • @user3581248 Even if he wants to fail silently, it's better to do it with the proper tech. You can eat with a shovel but it's better to do it with a fork. – Eric Aya May 16 '17 at 17:26
  • @EricAya and write a lot of redundant code just because URLSession is prettier? – user3581248 May 16 '17 at 17:29

0 Answers0