2012-06-22 4 views
7

私はライブラリを作成しているので、自分のメソッド内でAFNetworking呼び出しからの応答をカプセル化する必要があります。このコードは近い私を取得します。メソッド内のAFNetworkingから成功した失敗ブロックをラップする

MyDevice *devices = [[MyDevice alloc] init]; 
    [devices getDevices:@"devices.json?user_id=10" success:^(AFHTTPRequestOperation *operation, id responseObject) { 

    ... can process json object here ... 

} 

- (void)getDevices:(NSString *)netPath success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 
    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure { 
    [[MyApiClient sharedDeviceServiceInstance] getPath:[NSString stringWithFormat:@"%@", netPath] 
     parameters:nil success:success failure:failure]; 
} 

しかし、私は)getDevices(に戻る前にある、getPathから返されたJSONオブジェクトデータを処理する必要があります。 私はこれを試してみた:

- (void)getDevices:(NSString *)netPath success:(void (^)(id myResults))success 
     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure { 

    [[MyApiClient sharedDeviceServiceInstance] getPath:[NSString stringWithFormat:@"%@", netPath] 
    parameters:nil 
    success:^(AFHTTPRequestOperation *operation, id responseObject) 
    { 
    ... can process json object here ... 
    }       
    failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    ... process errors here ... 
    }]; 
} 

をしかし今はコールがgetDevicesに戻っはありません()。 getDevicesのjsonオブジェクトを処理するにはどうすれば完了時にブロックリターンを持つ&ですか? 私はブロックを初めて使うので、助けてくれてありがとう。

答えて

10

これは本当に簡単です:ブロックを関数のように呼び出すだけです。

- (void)getDevices:(NSString *)netPath 
      success:(void (^)(id myResults))success 
      failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure 
{ 
    [[MyApiClient sharedDeviceServiceInstance] 
    getPath:netPath 
    parameters:nil 
    success:^(AFHTTPRequestOperation *operation, id responseObject) 
    { 
     id myResults = nil; 
     // ... can process json object here ... 
     success(myResults); 
    }       
    failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     // ... process errors here ... 
     failure(operation, error); 
    }]; 
} 

EDIT:あなたは、私は次のインターフェイスをより明確になると思います掲載のコードに基づいて

typedef void(^tFailureBlock)(NSError *error); 

- (void)getDevicesForUserID:(NSString *)userID 
        success:(void (^)(NSArray* devices))successBlock 
        failure:(tFailureBlock)failureBlock; 
+0

あなたはphix23ありがとう! "success(myResults);を追加するとgetPath()successブロックに渡すと、すべてが期待通りに機能します。超高速応答に感謝します。 - Dan – Dan

+0

明快なコメントも気に入っています。機能性に重点を置いてきたが、これらの提案を最終版に組み込む予定である。 – Dan

+0

swiftでこのgetDevices関数が必要です。それをswiftに変換することはできますか –

関連する問題