2014-07-25 35 views
0

当我使用sendAsynchronousRequest方法的时候这个方法内块会在执行外部代码后执行?sendAsynchronousRequest方法会在块外代码前执行块代码

__block NSDictionary *dict; 
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) 
    { 
     NSInteger httpStatus = [((NSHTTPURLResponse *)response) statusCode]; 
     NSLog(@"httpStatus inside block:%d",httpStatus); 
     if ([data length]>0 && connectionError==nil) 
     { 
      dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil]; 
     } 
     else if (connectionError) 
     { 
      UIAlertView *alt=[[UIAlertView alloc] initWithTitle:@"Error" message:[connectionError localizedDescription] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
      [alt show]; 
     } 
    }]; 

return dict;//it will return null because it will run before execute inner block of sendAsynchronousRequest 
+0

添加完毕块来回报您的词典内容 – nanjunda

+0

是。这就是使该方法异步的原因。直到请求完成后才会调用“completionHandler”。这似乎是一个不完整的问题,也许你可以澄清你在问什么? – Jonah

回答

0

异步请求总是在网络线程中运行。 你的[NSOperationQueue mainQueue]意味着block-callback将在mainQueue中进行安排。 如果您想等到请求完成,您可以使用同步请求,或使用信号量来阻止当前线程。

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error; 

但要注意的是这种方式请求将阻止当前线程。使用这种方式时要小心。

+0

我可以使用这种方法,但是当我在那个时候使用这种方法'UIActivityIndi​​catorView'将不起作用 – Ronak

+0

你想要什么?阻止当前线程或在后台线程中运行。 – Suen

+0

'[self performSelectorInBackground:@selector(sendSynchronousRequest:returningResponse:error :) withObject:nil];'我可以用这个,但会出现错误 – Ronak

0

请用正楷方法

首先定义一个块

 typedef void (^OnComplate) (NSDictionary * dict); 
- (void)viewDidLoad{ 
    [self getDataWithBlokc:^(NSDictionary *dict) { 
     NSLog(@"%@",dict); 
    }]; 
} 

使用下面的方法

-(void)getDataWithBlokc:(OnComplate)block{ 
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) 
    { 
     NSInteger httpStatus = [((NSHTTPURLResponse *)response) statusCode]; 
     NSLog(@"httpStatus inside block:%d",httpStatus); 
     if ([data length]>0 && connectionError==nil) 
     { 
      NSDictionary* dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil]; 

      block(dict); 
     } 
     else if (connectionError) 
     { 
      UIAlertView *alt=[[UIAlertView alloc] initWithTitle:@"Error" message:[connectionError localizedDescription] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
      [alt show]; 
     } 
    }]; 
} 
+0

哪里调用这个方法? – Ronak

+0

您想要获取数据的位置。 –

+0

我将返回字典对象与数据.. – Ronak