我正在和一个网络控制的硬件设备交互。您通过URL (例如,http://device/on?port=1或http://device/off?port=3)发送一个请求来打开和关闭内容,并且它会返回“成功”或“失败”。但是,它是一个简单的设备,所以当它处理一个请求时--也就是说,直到它返回它正在处理的请求的状态--它将忽略所有后续请求。它不会让他们排队,他们只是迷路了。
所以我需要发送串行同步请求。例如,req#1,等待response#1,req#2,等待response#2,req#3,等待响应#3,等等。
我是否需要管理自己的线程安全请求队列,让UI线程将请求推送到队列的一端,并让另一个线程在前一个线程完成或超时后立即将请求取出,并将结果发送回UI线程?还是我在API中遗漏了一些已经这样做的东西?
谢谢!
...R
发布于 2012-08-27 19:20:03
应该使用的是NSOperationQueue实例,以及许多执行各种NSOperation请求的NSOperation实例。
首先,在类中设置一个队列,该队列将对请求进行排队。确保保持对它的强烈引用,即
@interface MyEnqueingClass ()
@property (nonatomic, strong) NSOperationQueue *operationQueue;
@end在实现的某个地方,比如init方法:
_operationQueue = [[NSOperationQueue alloc] init];
_operationQueue.maxConcurrentOperationCount = 1;您基本上需要一个串行队列,因此需要1的maxConcurrentOperationCount。
设置之后,您将需要编写如下代码:
[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?
}];通过这种方式,您可以发送同步NSURLRequest,并可以处理错误条件,包括完全退出并重新启动(调用-cancelAllOperations的行)。这些请求将一个接一个地执行。
当然,您也可以编写自定义的NSOperation子类和对这些类的实例进行排队,而不是使用块(如果这对您有用的话)。
希望这能帮上忙,如果你有什么问题请告诉我!
发布于 2012-08-27 19:00:10
您可以使用NSOperationQueue类,也可以使用构建在其上的一些API,例如AFNetworking。
https://stackoverflow.com/questions/12147512
复制相似问题