我使用AFNetworking
框架https://github.com/AFNetworking/AFNetworking。
一切顺利,但函数返回Null
,但一切正常NSLog
返回Null
。
可能是什么原因?
-(NSString *)cook
{
__block NSString *fecho =nil;
NSURL *baseURL = [NSURL URLWithString:@"http://google.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:@"Accept"];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:@"" parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
fecho = [[operation.response allHeaderFields] valueForKeyPath:@"Date"];
NSLog(@"%@",fecho);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
fecho = @"errr";
}];
[request setTimeoutInterval:20.0];
[operation start];
return fecho;
}
非常感谢!
答案 0 :(得分:2)
将-(NSString *)cook
更改为
- (void)cookOnCompletion:(void (^)(NSString *errorMessage))completion {
NSURL *baseURL = [NSURL URLWithString:@"http://google.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:@"Accept"];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:@"" parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *fecho = [[operation.response allHeaderFields] valueForKeyPath:@"Date"];
completion(fecho);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSString *error = @"errr";
completion(error);
}];
[request setTimeoutInterval:20.0];
[operation start];
}
并致电cookOnCompletion:
,如
[self cookOnCompletion:^(NSString *response){
NSLog(@"%@",response);
}];