Objective c NSURLConnection sendAsynchronousRequest:队列:completionHandler在iOS 4.3中不工作
我正在我的应用程序中使用Objective c NSURLConnection sendAsynchronousRequest:队列:completionHandler在iOS 4.3中不工作,objective-c,ios,ios5,nsurlconnection,ios4,Objective C,Ios,Ios5,Nsurlconnection,Ios4,我正在我的应用程序中使用[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]completionHandler:^(NSURResponse*response,NSData*data,NSError*error)。通过使用此选项,我的应用程序在iOS 4.3中终止,但在iOS 5.0中运行正常 如何在iOS 4.3中使用这一点可以帮助我。< P>你试图使用的方法只能在iOS 5上使用
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]completionHandler:^(NSURResponse*response,NSData*data,NSError*error)
。通过使用此选项,我的应用程序在iOS 4.3中终止,但在iOS 5.0中运行正常
如何在iOS 4.3中使用这一点可以帮助我。
< P>你试图使用的方法只能在iOS 5上使用。对于较早的OSES,考虑使用< /P>+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
并将其包装到新线程中以实现异步行为。关于H2CO3和Ken Thomases的建议都是正确的 另外,你可以看看 如果使用主队列作为完成处理程序执行的队列,则可以使用(如Tom建议的)委托模式。为了避免重复代码,可以在
NSURLConnection
委托机制上使用包装器
在另一种情况下,如果您想保持异步行为,而不想处理同步调用(如建议的那样,请注意他的建议也是有效的)完成处理程序在不同的队列中执行,然后我建议您将异步委托模式包装在NSOperation
类中。这种方法非常困难,但您可以在中找到一种很好的方法(参见两篇文章)
希望它能有所帮助。这是一个对我有用的完整实现。请随意重命名它并将其添加为
NSURLConnection
上的一个类别,或者将其作为本地方法添加到您正在使用的类中
-(void)sendAsynchronousRequest:(NSURLRequest*)request queue:(NSOperationQueue*)queue completionHandler:(void(^)(NSURLResponse *response, NSData *data, NSError *error))handler
{
__block NSURLResponse *response = nil;
__block NSError *error = nil;
__block NSData *data = nil;
// Wrap up synchronous request within a block operation
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
}];
// Set completion block
// EDIT: Set completion block, perform on main thread for safety
blockOperation.completionBlock = ^{
// Perform completion on main queue
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
handler(response, data, error);
}];
};
// (or execute completion block on background thread)
// blockOperation.completionBlock = ^{ handler(response, data, error); };
// Execute operation
[queue addOperation:blockOperation];
}
编辑
我不得不修改这个方法,因为我在完成块中调用UIKit(例如更新标签等)。因此在主线程上调用完成块实际上更安全一些。(原始版本被注释掉)第一步:使用一个合理简短的标题并格式化您的代码。最好继续使用
NSURLConnection
的异步行为,在主线程的运行循环上安排一个适当的委托。@kenthomass-有什么具体的原因让它更好吗?H2CO3不是准确描述了这种方便方法的用途吗?是ju吗是否要阻止线程?是的。由于NSURLConnection
提供了异步模式,因此没有理由创建线程只是为了防止它阻止主线程。