1

I wanted to translate this in swift :

dispatch_async(kBgQueue, ^{

        NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];

        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];

    });

It's for using google places api.

I wondering about using a simple NSURLSession request but it seems that the dataWithContentsOfURL do the job of an NSURLSession request ?

Someone ?

Aymenworks
  • 423
  • 7
  • 21

2 Answers2

1

dataWithContentsOfURL is discouraged. You should use NSURLSession for asynchronous downloads, or if you prefer the simpler NSURLConnection.

The delegate callbacks tell the main thread when the download is finished - so no need to engage with Great Central Dispatch APIs.

Mundi
  • 79,884
  • 17
  • 117
  • 140
0

Mundi is right that the better tool here is NSURLSession. But your code can work; just need to use GCD correctly, and deal with the fact that it might fail:

dispatch_async(kBgQueue) {
    if let data = NSData.dataWithContentsOfURL(googleRequestURL) {
      dispatch_sync(dispatch_get_main_queue()) { self.fetchedData(data) }
    } else {
      // Here's the problem with dataWithContentsOfURL. You had an error, but you
      // don't know what it was. I guess you'll do something here...
    }
}
Rob Napier
  • 286,113
  • 34
  • 456
  • 610