[英]How to use the values out of sendAsynchronousRequest?
我正在使用Http POST請求和NSURLRequest解析一些JSON數據。 但是,當我在sendAsynchronousRequest下獲得了值時,我將無法使用該請求之外的值。 請參見下面的示例:
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSError *parseError = nil;
dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(@"Server Response (we want to see a 200 return code) %@",response);
NSLog(@"dictionary %@",dictionary);
}];
我的查詢是如何在需要的地方使用字典值? 謝謝
您可以通過多種方式進行操作。 一種方法是聲明屬性並在塊內使用它。
當您撥打異步電話時,最好有自己的自定義塊來響應這些電話。
首先聲明一個完成塊:
typedef void (^ ResponseBlock)(BOOL success, id response);
並聲明一個使用此塊作為參數的方法:
- (void)processMyAsynRequestWithCompletion:(ResponseBlock)completion;
並在此方法中包括您的異步調用:
- (void)processMyAsynRequestWithCompletion:(ResponseBlock)completion{
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSError *parseError = nil;
dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(@"Server Response (we want to see a 200 return code) %@",response);
NSLog(@"dictionary %@",dictionary);
completion(YES,response); //Once the async call is finished, send the response through the completion block
}];
}
您可以在任何需要的地方調用此方法。
[classInWhichMethodDeclared processMyAsynRequestWithCompletion:^(BOOL success, id response) {
//you will receive the async call response here once it is finished.
NSDictionary *dic = (NSDictionary *)response;
//you can also use the property declared here
_dic = (NSDictionary *)response; //Here dic must be declared strong
}];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.