1

When you create/update/delete a record in my app it creates an OutgoingRequest in Core Data. Periodically, the app will get these requests in a queue, and push them all to the server. I do this using a AFHTTPClient post (seen below). The issue I am running into is that it pushes all of these requests up at one time, then the responses come back in no real order.

What I need to do is make these requests work 'synchronically' in that request B should not be posted until request A has finished (success or fail response). This is done in the background as well, and should not hang the UI.

for(OutgoingRequest *req in queue)
{
    NSURL *reqUrl = [NSURL URLWithString: globals.baseURL];
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:reqUrl];
    [httpClient setParameterEncoding:AFJSONParameterEncoding];

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            req.url, @"viewName",
                            req.json, @"JSON",
                            req.dateAdded.description, @"dateTime",
                            nil];

    NSString *path = [NSString stringWithFormat:@"cache/update/?deviceUID=%@&token=%@", [MySingleton getMacAddress],  globals.token];

    [httpClient postPath:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

            //handle the repsonse

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}

Is there any way to achieve this with my current setup? Or should I be using other means to POST to my server?

Thanks

4

2 に答える 2

1

が管理する内部NSOperationQueueを確認することをお勧めします。AFHTTPClientを 1 に設定しmaxConcurrentOperationCountてシリアル キューにすることができます。したがって、リクエストは、キューに追加した順序で一度に 1 つずつ実行されます。

これは、operationQueueAFHTTPClient の読み取り専用プロパティです。

/**
The operation queue which manages operations enqueued by the HTTP client.
*/
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;

クライアントのセットアップをどこで行う場合でも、同時操作数を 1 に設定します。

myHTTPClient.operationQueue.maxConcurrentOperationCount = 1;

ネットワーク リクエストに関しては、いずれにせよシリアル キューを使用することをお勧めします。結局のところ、同時リクエストの数は、サーバーで開くことができる HTTP 接続の数と、デバイスのアンテナの帯域幅によって制限されます。どちらにも上限があります。

于 2013-11-01T16:57:30.550 に答える