2

我正在与网络控制的硬件设备进行交互。您通过 URL(例如http://device/on?port=1http://device/off?port=3)向它发送一个请求以打开和关闭某些东西,然后它发回“成功”或“失败”。然而,它是一个简单的设备,所以在它处理请求时——,直到它返回它正在处理的请求的状态——它将忽略所有后续请求。它不会将它们排队;他们只是迷路了。

所以我需要发送串行、同步的请求。,req#1,等待响应#1,req#2,等待响应#2,req#3,等待响应#3,等等。

我是否需要管理我自己的线程安全请求队列,让 UI 线程将请求推送到队列的一端,并让另一个线程将请求拉出,一次一个,只要前一个完成或超时,并将结果发送回 UI 线程?还是我在 API 中遗漏了一些已经做到这一点的东西?

谢谢!

...R

4

2 回答 2

3

应该工作的是使用一个NSOperationQueue实例,以及NSOperation执行各种 URL 请求的多个实例。

首先,在类中设置一个队列,将请求排入队列。确保保持对它的强烈引用,即

@interface MyEnqueingClass ()

@property (nonatomic, strong) NSOperationQueue *operationQueue;

@end

在实现的某个地方,说init方法:

    _operationQueue = [[NSOperationQueue alloc] init];
    _operationQueue.maxConcurrentOperationCount = 1;

你基本上想要一个串行队列,因此maxConcurrentOperationCount是 1。

设置完成后,您将需要编写如下代码:

[self.operationQueue addOperationWithBlock:^{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"my://URLString"]];
    NSError *error;
    NSURLResponse *response;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (!responseData)
    {
        //Maybe try this request again instead of completely restarting? Depends on your application.
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            //Do something here to handle the error - maybe you need to cancel all the enqueued operations and start again?
            [self.operationQueue cancelAllOperations];
            [self startOver];
        }];
    }
    else
    {
        //Handle the success case;
    }
}];

[self.operationQueue addOperationWithBlock:^{
    //Make another request, according to the next instuctions?
}];

通过这种方式,您发送同步NSURLRequests 并可以处理错误情况,包括完全退出并重新开始(带有-cancelAllOperations被调用的行)。这些请求将一个接一个地执行。

当然,您也可以编写自定义NSOperation子类并将这些实例排入队列,而不是使用块,如果这对您有用的话。

希望这会有所帮助,如果您有任何问题,请告诉我!

于 2012-08-27T19:20:03.493 回答
0

您可以使用NSOperationQueue 类,也可以使用一些内置的 API,例如AFNetworking

于 2012-08-27T19:00:10.923 回答