我为当前正在编写的应用程序编写了一个同步类。异步数据连接iOS
由于数据量大,它首先获得数据计数,然后在NSOperationQueue
中批量下载。这一切工作正常,我有快速工作的同步算法。
它的工作方式如下:...
- (void)synchroniseWithCompletionHandler://block for completion handler
errorHandler://block for error handler
{
[self.queue addOperationWithBlock
^{
//Create an NSURLRequest for the first batch
//Send the request synchronously
//Process the result
//If error then cancel all operations in the queue, run errorHandler and return.
}];
[self.queue addOperationWithBlock
^{
//Create an NSURLRequest for the second batch
//Send the request synchronously
//Process the result
//If error then cancel all operations in the queue, run errorHandler and return.
}];
//Add all the remaining batches.
[self.queue addOperationWithBlock
^{
completionHandler();
}];
}
这工作,并保持内存使用到最低限度,速度最大。这个想法是,下载和进程都在同一个块中,并在进入队列中的下一个操作之前进行处理。
除了我们现在在服务器上实现OAuth2来验证呼叫。
我已经通过NXOAuth2库设置了一个NXOAuth2Request来实现这个工作。然后设置帐户并提取签名的URL请求。然后我使用这个NSURLRequest,就像我之前做的那样。
问题是,如果OAuth令牌在同步中途过期,则同步失败。
的NXOAuth2库有一个函数...
+ (void)performMethod:(NSString *)aMethod
onResource:(NSURL *)aResource
usingParameters:(NSDictionary *)someParameters
withAccount:(NXOAuth2Account *)anAccount
sendProgressHandler:(NXOAuth2ConnectionSendingProgressHandler)progressHandler
responseHandler:(NXOAuth2ConnectionResponseHandler)responseHandler;
这通过重新发送做一个标记后刷新请求处理过期令牌的情况。
但是,这个功能是异步的,所以我不知道如何最好地将它适用于我的同步程序。
我可以使用此操作添加操作,然后将处理放入完成块。但是这样做意味着所有下载将几乎同时运行,然后无法保证下载得到处理的顺序(由于数据依赖性,我需要以严格的顺序处理它们)。
我觉得现在这样做的唯一方法是菊花链它们放在一起......
[NXOAuth2Request performFirstRequest...
{
deal with the data.
[NXOauth2Request performSecondRequest...
{
deal with the data.
[NXOauth2Request performThirdRequest...
{
deal with the data.
finish
}];
}];
}];
而这仅仅是凌乱而能得到非常混乱。
是否有任何其他方式我可以处理这个问题吗?我唯一能想到的其他事情就是尝试自我提神。
是的,我没有想到NSOperation subclassassing。 (TBH以前从未正确完成过)。也没有意识到你可以阻止来自NSOperation内的异步调用。谢谢,会看看。 – Fogmeister
你可能会添加一个链接到你的github项目?谢谢 – Fogmeister
完成 - 它在编辑答案 –