我在一个类中使用 block 从响应中获取 header 字段,我必须在另一个类中获取它。
我实现了这样的代码
头等舱:
- (void)viewDidLoad {
[super viewDidLoad];
UserAuthentication *auth = [[UserAuthentication alloc]init];
NSDictionary *dict = [auth getUserConfiguration];
NSLog(@"%@",dict);
}
在 userAuthentication 类中:
-(NSDictionary *)getUserConfiguration;
{
__block NSDictionary *resultDictionary;
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:@"http://72.52.65.142:8083/auth"]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
resultDictionary = [httpResponse allHeaderFields];
NSLog(@"%@",resultDictionary);
}
}] resume];
NSLog(@"%@",resultDictionary);
return resultDictionary;
}
我的问题是在头等舱,我得到的 dict
为 null。
即使在 userAuthentication
类中我也得到 null。
但一段时间后回调方法正在调用,然后我可以在 completionHandler
中正确看到响应。
那么我如何才能在 firstClass 中获得响应?
最佳答案
您误解了在后台线程中运行的异步操作的基本原理,当操作完成时,它会在完成 block 中为您提供数据。
要在第二类的 viewDidLoad 方法中获得响应,您需要使用 block 。如下图
-(void)getUserConfigurationOnCompletion:(void (^)(NSDictionary *))completion
{
__block NSDictionary *resultDictionary;
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:@"http://72.52.65.142:8083/auth"]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
resultDictionary = [httpResponse allHeaderFields];
// Call completion with parameter
completion(resultDictionary);
}
}] resume];
}
然后在 viewDidLoad 中像这样使用它
- (void)viewDidLoad {
[super viewDidLoad];
UserAuthentication *auth = [[UserAuthentication alloc]init];
[auth getUserConfigurationOnCompletion:^(NSDictionary *dict){
// do necessary work with response dictionary here
NSLog(@"%@",dict);
}];
}
关于ios - 如何立即得到 block 中的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40104610/