-2

I'm new for development learning to parsing the data and how to work with synchronous and asynchronous requests.

NSString *url=@"http://content.guardianapis.com/search?api-key=test";

NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSError *error=nil;
NSURLResponse *response;
NSData *content=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *string=[[NSString alloc]initWithData:content encoding:NSUTF8StringEncoding];
NSLog(@"response %@",string);

I receive a warning at the sendSynchronousRequest line. How do I process this asynchronously web request and get the response data. Explain difference of both.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
saravanar
  • 639
  • 2
  • 11
  • 25

1 Answers1

0

Two separate issues here.

  1. First, the request should be asynchronous and use NSURLSession. For example:

    NSURL *url = [NSURL URLWithString:@"http://content.guardianapis.com/search?api-key=test"];
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@", error);
            return;
        }
    
        NSError *parseError;
        NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    
        if (responseObject) {
            NSLog(@"%@", responseObject);
            dispatch_async(dispatch_get_main_queue(), {
                // if you want to update your UI or any model objects,
                // do that here, dispatched back to the main queue.
            });
        } else {
            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"problem parsing response, it was:\n%@", string);
        }
    }];
    [task resume];
    
    // but do not try to use `data` here, as the above runs asynchronously
    // do everything contingent upon this request _inside_ the completion 
    // handler above
    

    Note, when you get the JSON response, you can parse that with NSJSONSerialization, as shown above.

  2. Nowadays, using http for requests is frowned upon because it's not secure. You generally should use https. And NSURLSession will enforce this, returning an error if you try to use http. But if you want to force it to permit an insecure http request, you have to update your info.plist with an entry that looks like:

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSExceptionDomains</key>
      <dict>
        <key>guardianapis.com</key>
        <dict>
          <!--Include to allow subdomains-->
          <key>NSIncludesSubdomains</key>
          <true/>
          <!--Include to allow HTTP requests-->
          <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
          <true/>
          <!--Include to specify minimum TLS version-->
          <key>NSTemporaryExceptionMinimumTLSVersion</key>
          <string>TLSv1.1</string>
        </dict>
      </dict>
    </dict>
    

    So, go to your info.plist, control-click on it and choose "Open As" ... "Source Code" and then add the above into it. See https://stackoverflow.com/a/31254874/1271826 for more information.

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • how to use this in synchronous. what is the difference between synchronous and asynchronous requests. – saravanar Mar 18 '16 at 07:21
  • @saravanar - Synchronous means "block the thread while the request takes place", whereas asynchronous means the exact opposite, namely that the current thread won't be blocked and that the code in the completion handler will be called asynchronously (i.e. later). You almost never want to perform synchronous requests (because if you do this from the main thread, you'll block the main thread, which can lead to all sorts of problems). `NSURLSession` doesn't even offer synchronous requests. It may take a little time to really familiarize yourself with asynchronous programming, but it's critical. – Rob Mar 18 '16 at 08:30
  • the request should be asynchronous and use NSURLSession. how to use synchronous.. – saravanar Mar 18 '16 at 13:06
  • @saravanar - You don't generally do synchronous requests anymore, because it results in a horrible UI (app will freeze while request is underway) and watchdog process might actually kill your app if you freeze at an inopportune time. If you explain why you think you need synchronous request and we can help you solve that. – Rob Mar 18 '16 at 13:51
  • If you're asking when, more generally, you perform synchronous tasks, here's an example: Sometimes you have some property that you need to access from multiple threads. To ensure thread-safety, you synchronize that access and you can use `dispatch_sync` to some serial queue when you want to read that property. It's generally going to be exceptionally quick, but ensures you aren't mutating that property from one thread while reading it from another. You wouldn't do that very often (and definitely avoid doing anything slow, like network request, synchronously), but it's one example. – Rob Mar 21 '16 at 19:15