2015-10-25 4 views
0

Я пытаюсь обработать данные для каждого запроса до того, как будет сделан последующий запрос. Здесь есть два метода, а второй метод вызывается из первого метода, используя dispatch_semaphore, чтобы гарантировать, что запрос завершен, однако это не будет ждать, пока ответ фактически не будет получен/обработан. Это приводит к тому, что диаграмма создается не в правильном порядке, и иногда имена папок отображаются неверными данными.Как подождать, пока NSURLResponse будет обработан для повторения цикла?

- (void)load:(NSData*)data completionHandler:(void(^)(NSURLResponse *response, NSData *data, NSError *error))handler 

{ 
    NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

    NSLog(@"Loading... %@", s); 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

    NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; //allows for SSL connections 

    [request setHTTPMethod:@"POST"]; 

    [request setHTTPBody:data]; 

    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] 

          completionHandler:handler]; 

    [urlConnection start]; //start connection after request 
} 

//issue is occurring within this method 
- (void)GetPOActivity:(NSString*)aliasname completionhandler:(void (^)(NSDictionary *, NSError *))handler; 
{ 
    NSMutableDictionary *d = [[NSMutableDictionary alloc] init]; 

    [d setValue:interface forKey:@"interface"]; 

    [d setValue:@"GetDocsPerDay" forKey:@"method"]; 

    NSMutableDictionary *p = [[NSMutableDictionary alloc] init]; 

    NSString *cno = [[NSUserDefaults standardUserDefaults] objectForKey:@"cno"]; 

    [p setValue:aliasname forKey:@"aliasname"]; 

    [d setValue:p forKey:@"parameters"]; 

    NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil]; 

    [self load:data completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 

     NSLog(@"done"); 

     NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

     NSLog(@"GetDocsPerDay RAW response = %@", s); 

     //checks if data is null or server unavailable 
     if (apiConditions) 
     { 
      dispatch_async(dispatch_get_main_queue(), 
          ^{ 
           [hud hide:YES]; 
           NSLog(@"data is NIL"); 
          }); 
      [hud hide:YES]; 

     } 
     else 
     { 
      //get values 
      NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
      handler(d, error); 
      NSMutableString *partnerString = d[@"Value"]; 
      NSArray *trArray = [[NSArray alloc] init]; 
      NSDictionary *trDict; 
      trArray = partnerString; 
      NSInteger arrayCount; 

      arrayCount = trArray.count; 

      for (int i = 0; i < arrayCount; i++) 
      { 
       trDict = trArray[i]; 
       //NSString *aliasNameString; 
       //aliasNameString = test[@"AliasName"]; 


       if (d[@"Value"][i][@"folder"]!=nil)[folders addObject:d[@"Value"][i][@"folder"]]; 
       NSLog(@"folder is %d %@",i,d[@"Value"][i][@"folder"]); 

       NSLog(@"%d",i); 

      } 

      dispatch_semaphore_t sema = dispatch_semaphore_create(folders.count); 

      int i = 0; 

      for (NSString *folder in folders) 
      { 
       NSCalendar *calendar = [NSCalendar currentCalendar]; 

       NSDate *date = [NSDate date]; 

       NSDateComponents *components = [[NSDateComponents alloc] init]; 

       [components setWeek:-1]; 

       NSDate *lastweek = [calendar dateByAddingComponents:components toDate:date options:0]; 

       NSLog(@"%@", lastweek); 

       NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
       formatter.dateFormat = @"MM-dd-yyyy"; 
       NSString *today = [formatter stringFromDate:[NSDate date]]; 
       NSString *prevWeek = [formatter stringFromDate:lastweek]; 

       [self GetPOActivity2:aliasname startdate:prevWeek enddate:today document:folder completionhandler:^(NSDictionary *dictionary, NSError *error) { 
        dispatch_semaphore_signal(sema); 
        if (i == folders.count-1) 
        { 
         dispatch_async(dispatch_get_main_queue(), 
             ^{ 
              //[hud hide:YES]; 
              [self initFakeData]; 
             }); 
        } 


       }]; 

       i++; 
       dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); 
      } 

      [hud hide:YES]; 

     }//end of else statement 

    }];//end of block 
} 

//final method called within loop 
- (void)GetPOActivity2:(NSString*)aliasname startdate:(NSString*)startdate enddate:(NSString*)enddate document:(NSString*)document completionhandler:(void (^)(NSDictionary *, NSError *))handler; 
{ 
    NSMutableDictionary *d = [[NSMutableDictionary alloc] init]; 

    [d setValue:interface forKey:@"interface"]; 

    [d setValue:@"GetDocsPerDay2" forKey:@"method"]; 

    NSMutableDictionary *p = [[NSMutableDictionary alloc] init]; 

    [p setValue:aliasname forKey:@"aliasname"]; 
    [p setValue:startdate forKey:@"startdate"]; 
    [p setValue:enddate forKey:@"enddate"]; 
    [p setValue:document forKey:@"document"]; 

    [d setValue:p forKey:@"parameters"]; 

    NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil]; 

    [self load:data completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 

     NSLog(@"done"); 

     NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

     NSLog(@"GetDocsPerDay2 RAW response = %@", s); 

     //checks if data is null or server unavailable 
     if (apiConditions) 
     { 
      dispatch_async(dispatch_get_main_queue(), 
          ^{ 
           [hud hide:YES]; 
           NSLog(@"data is NIL"); 
          }); 
      [hud hide:YES]; 

     } 
     else 
     { 
      //get values 
      NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
      handler(d, error); 
      NSMutableString *partnerString = d[@"Value"]; 
      NSArray *trArray = [[NSArray alloc] init]; 
      NSDictionary *trDict; 
      trArray = partnerString; 
      NSInteger arrayCount; 

      arrayCount = trArray.count; 

      JBdataCount = arrayCount; 
      for (int i = 0; i < arrayCount; i++) 
      { 
       trDict = trArray[i]; 

       if (d[@"Value"][i][@"data"]!=nil) 
       { 
        [dataArray addObject:d[@"Value"][i][@"data"]]; 

        NSString *tempMonth = @""; //used for month name 
        tempMonth = [self convertMonthToString:d[@"Value"][i][@"month"]]; 

        [dateArray addObject:[NSString stringWithFormat:@"%@, %@ %@",tempMonth,d[@"Value"][i][@"day"],d[@"Value"][i][@"year"]]]; 
       } 
       NSLog(@"data is %d %@",i,d[@"Value"][i][@"data"]); 
       NSLog(@"%d",i); 

      } 
      [hud hide:YES]; 

     }//end of else statement 

    }];//end of block 
} 

ответ

1

Честно говоря, лучшим решением здесь является использование что-то вроде PromiseKit.