title: Wait until NSURLConnection sendAsynchronousRequest is finished
body: <p>I have the following problem. I have a Model, called User. When the user now logins with Facebook, my app checks if the user exists already in the database. To not freeze the UI (since I'm coming from Android) I thought to use <code>NSURLConnection sendAsynchronousRequest</code>. What worked at first was the following:</p>
  
  <p>My User Model had a method to do the whole task of the <code>AsynchronousRequest</code> and then when finished would set a variable to loading. Then other classes, could simply check with 
  <code>while ( !user.loading )</code> if the Request was finished or not. The problem that came here to me, was, that now, I had to put this method in every Model. So instead of this, I created a new Class <code>HTTPPost</code>. This class now has the method that gets an <code>NSDictionary</code> passed and returns one. This works ALMOST. The problem I was now encountering is, that I couldn't really determine if the process was finished or not. So I started to create a new class called <code>Globals</code> and use global Variable <code>loading</code>. But the global variable is ALWAYS NO. So, what would be the best way to do this?</p>
  
  <p>Here is my code:</p>
  
  <p>This is where I check for the user and load it. <code>resultDictionary</code> is the <code>NSDictionary</code> where everything gets loaded in, but is always <code>nil</code></p>
  
  <pre><code> [user loadModelFrom:[NSString stringWithFormat:@"WHERE facebookId='%@'", graphUser.id]];
          NSLog(@"%@", user.resultDictionary);
          if ( user.resultDictionary == nil ) {
              NSLog(@"NIL");
          } else {
              NSLog(@"NOT NIL");
          }
  </code></pre>
  
  <p>The problem now, is, that, since I'm sending an AsynchronousRequest, the resultDictionary is always nil. What I did before and worked was the following.</p>
  
  <p>In my Model I had the HTTP Request and a variable named <code>loading</code>. Now I set loading to false until the response has been made into a <code>NSDictionary</code></p>
  
  <pre><code>returnDict = [NSJSONSerialization JSONObjectWithData: [responseBody dataUsingEncoding:NSUTF8StringEncoding]
                                                                     options: NSJSONReadingMutableContainers
                                                                       error: &amp;error];
  </code></pre>
  
  <p>But, then I had another problem. I had to do this in all my Models again... So I created a new Class that subclasses NSObject, that has the asynchronousRequest. This is the whole request</p>
  
  <pre><code>-(NSDictionary *)doHttpRequest:(NSDictionary *)postDict{
      loading = NO;
      __block NSDictionary *returnDict;
      NSError *error;
      NSString *jsonString;
      NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict
                                                         options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                           error:&amp;error];
  
      if (! jsonData) {
          NSLog(@"Got an error: %@", error);
      } else {
          jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
      }
  
      NSURL *aUrl = [NSURL URLWithString:@"http://xx.xx-xx.xx/xx.xx"];
      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                         timeoutInterval:60.0];
      NSOperationQueue *queue = [[NSOperationQueue alloc] init];
      NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"xx", @"xx"];
      NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
      NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];
      [request setValue:authValue forHTTPHeaderField:@"Authorization"];
      [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
      [request setHTTPMethod:@"POST"];
      [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
  
      [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
       {
           NSString *responseBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
           returnDict             = [NSJSONSerialization JSONObjectWithData: [responseBody dataUsingEncoding:NSUTF8StringEncoding]
                                                                     options: NSJSONReadingMutableContainers
                                                                       error: &amp;error];
  
       }];
      [queue waitUntilAllOperationsAreFinished];
      loading = YES;
      return returnDict;
  }
  </code></pre>
  
  <p>As you can see I have now a variable called <code>loading</code>. It is a global variable. But somehow, the variable is always NO. </p>
  
  <p>What would be the best way to do this? I hope I'm understandable, I'm new to Objective-C, and English isn't my native language.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I modified the code to look like a user provided here, but still not working!</p>
  
  <pre><code>HTTPPost.h
  -(void)doHttpRequest:(NSDictionary *)postDict completion:(void(^)(NSDictionary *dict, NSError *error))completion {
      __block NSDictionary *returnDict;
      NSError *error;
      NSString *jsonString;
      NSString *authValue;
      NSString *authStr;
  
      NSData *jsonData;
      NSData *authData;
      NSURL *aUrl;
      NSMutableURLRequest *request;
      NSOperationQueue *queue;
  
  
      jsonData = [NSJSONSerialization dataWithJSONObject:postDict
                                                         options:NSJSONWritingPrettyPrinted
                                                           error:&amp;error];
  
      if (! jsonData) {
          NSLog(@"Got an error: %@", error);
      } else {
          jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
      }
  
      aUrl        = [NSURL URLWithString:@"http://xx.xx-xx.com/xx.php"];
      request     = [NSMutableURLRequest  requestWithURL:aUrl
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                             timeoutInterval:60.0];
  
      queue       = [[NSOperationQueue alloc] init];
      authStr     = [NSString stringWithFormat:@"%@:%@", @"xx", @"xx"];
      authData    = [authStr dataUsingEncoding:NSASCIIStringEncoding];
      authValue   = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];
      [request setValue:authValue forHTTPHeaderField:@"Authorization"];
      [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
      [request setHTTPMethod:@"POST"];
      [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
  
      [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
       {
           NSString *responseBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
           returnDict             = [NSJSONSerialization JSONObjectWithData: [responseBody dataUsingEncoding:NSUTF8StringEncoding]
                                                                    options: NSJSONReadingMutableContainers
                                                                      error: &amp;error];
           if ( completion ) {
               completion(returnDict, error);
           }
       }];
  }
  
  //User.h
  [_httpPost doHttpRequest:_dbDictionary completion:^(NSDictionary *dict, NSError *error) {
      NSLog(@"completed") // NEVER GETS FIRED
  }];
  </code></pre>