2013-08-31 13 views
5
-(void)getDataFromServer: (NSMutableDictionary *)dict 
{ 

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/doSomething",MainURL ]]; 
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]]; 

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:nil parameters:dict]; 

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) 
{ 
    _myArray = JSON; 
    [_myTableView reloadData]; //Or do some other stuff that are related to the current `ViewController` 
} 
failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON) 
{ 
    NSLog(@"request: %@",request); 
    NSLog(@"Failed: %@",[error localizedDescription]); 
}]; 

[httpClient enqueueHTTPRequestOperation:operation]; 
} 

私のアプリの7つの場所で上記のコードを使用しています。コードの正確な塊は私のViewControllersの7に複製されています。私が通常使っていたのは、NSObjectクラスで使用したいメソッドを配置し、必要なときにそれを割り当てて使用することですが、上記のAsyncとブロックを使用しているため、JSONをViewControllerに返すことはできませんそれ、私はそれで必要なすべてのViewControllerで、上記の方法を貼り付け&をコピーする必要があります。AFNetworkingメソッドにブロックを渡しますか?

私の目標は私のアプリで唯一の場所で上記を持っており、今でも私のアプリの周りに異なるViewControllersからそれを呼び出すことができるようにすることですし、必要なデータを取得します。 私はNSNotificationまたはKVOのようなオブザーバを使わず、より洗練されたソリューションを探しています。 読んだ後、私はブロックを周回する可能性に気づいた。それは上記の可能な解決策ですか?コード例は高く評価されます。

+1

下記のGabrieleの回答に加えて、リクエストごとに新しいAFHTTPClientを回転させないようにすることができます。 –

+0

私はその答えを正確に編集していました。メモをありがとう。 –

答えて

6

因子分解

+ (void)getDataFromServerWithParameters:(NSMutableDictionary *)params completion:(void (^)(id JSON))completion failure:(void (^)(NSError * error))failure { 
    NSString * path = @"resources/123"; 
    NSMutableURLRequest *request = [self.httpClient requestWithMethod:@"POST" path:path parameters:params]; 
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
     if (completion) 
      completion(JSON); 
    } failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON) { 
     if (failure) 
      failure(error); 
    }]; 

    [httpClient enqueueHTTPRequestOperation:operation]; 
} 

のようなものへのAPI呼び出しあなたがXYAPIのようなユーティリティクラスでこのメソッドを配置し、ちょうどまた、あなたが必要としない

[XYAPI getDataFromServer:params completion:^(id JSON){ 
    // do something, for instance reload the table with a new data source 
    _myArray = JSON; 
    [_myTableView reloadData]; 
} failure:^(NSError * error) { 
    // do something 
}]; 

のようなあなたのコントローラからそれを呼び出すことができます要求ごとに新しいAFHTTPClientを生成します。 XYAPIクラスの共有コンポーネントを設定して使用します。何かのように

+ (AFHTTPClient *)httpClient { 
    static AFHTTPClient * client = nil; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
     client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://foo.com/api/v1/"]]; 
     [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]]; 
    }); 
    return client; 
} 

この実装はすでに上の例で使用されています。
selfはクラスメソッドのコンテキストではクラスそのものなので、self.httpClientは実際には実行時に[XYAPI httpClient]と解決されます。

+0

すばらしい答え!非常に詳細できれいに書かれています。私はそれをテストして報告します。どうもありがとう。 – Segev

関連する問題