ios - AFNetworking 返回函数

标签 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;
}

非常感谢!

最佳答案

改变 -(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);
}];

关于ios - AFNetworking 返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22087908/

上一篇:ios - 无法使以编程方式创建的 UITextField 可编辑 (iOS)

下一篇:iOS 应用暂停超时

相关文章:

iphone - libxml2 示例(带有包装器)

ios - UITableViewCell 图片来自网络

ios - 出于内存原因,NSMutableArray 是否比 NSArray 更好?

ios - 角标(Badge)号码不会清除

iOS swift : How to hide and reveal a button in UIViewController

objective-c - 使用 NSTextField 创建标签是模糊的

iphone - 为 UIView 自定义 initWithFrame

iphone - 如何在通用应用程序的ViewController中设置UIImageView框架?

objective-c - AFNetworking - 保存下载的文件

ios - 如何使用 AFNetworking 创建 JSON 数组