AFNetworking返回功能

时间:2014-02-28 06:32:05

标签: ios objective-c afnetworking

我使用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;
}
非常感谢!

1 个答案:

答案 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);
}];