如何等到处理完 NSURLResponse 后才遍历循环?
How to wait until NSURLResponse is processed to iterate through loop?
我试图在发出后续请求之前处理每个请求的数据。这里有两个方法,第二个方法是从第一个方法中使用 dispatch_semaphore 调用以确保请求完成,但是,这不会等到响应实际上已经 received/processed 出现。这会导致正在制作的图表无法按正确的顺序制作,有时文件夹名称会显示错误的数据。
- (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
}
老实说,这里最好的解决方案是使用 PromiseKit.
我试图在发出后续请求之前处理每个请求的数据。这里有两个方法,第二个方法是从第一个方法中使用 dispatch_semaphore 调用以确保请求完成,但是,这不会等到响应实际上已经 received/processed 出现。这会导致正在制作的图表无法按正确的顺序制作,有时文件夹名称会显示错误的数据。
- (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
}
老实说,这里最好的解决方案是使用 PromiseKit.