2014-02-28 139 views
0

我使用AFNetworking框架https://github.com/AFNetworking/AFNetworking。 一切都好,但函數返回Null,但一切都很好NSLog返回Null。 可能是什麼原因?AFNetworking返回功能

-(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

'fecho'只會操作完成後值分配,無論是成功還是失敗。這裏'fecho'在操作完成之前返回。 – Akhilrajtr

+0

'Google.com'沒有任何關鍵'日期' – preetam

+0

Akhilrajtr,如何等待和運行? – user3363589

回答

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