假设你不需要NSURLConnection
过程的基于委托的版本,某些其他原因,这是一个很好的用例的基于块的版本:
- (void)shareContentAtURL:(NSURL *)shareURL viaService:(NSString *)service
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:shareURL];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] == 0 && error == nil) {
// handle empty response
} else if (error != nil) {
// handle error
} else {
// back to the main thread for UI stuff
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// do whatever you do to get something you want to post from the url content
NSString *postText = [self postTextFromData:data];
// present the compose view
SLComposeViewController *vc = [SLComposeViewController composeViewControllerForServiceType:service];
[vc setInitialText:postText];
[self presentViewController:vc animated:YES];
}];
}
}];
}
由于块可以捕获周围范围内的变量,因此您可以使用已有的用于在NSURLConnection
的完成块内用户选择服务的任何上下文。
如果您仍然与基于代理的NSURLConnection
API无论出于何种原因都结婚,那么您总是可以使用伊维尔或其他某个状态附加到处理此过程的任何对象:设置self.serviceType
或某些此类用户选择一项服务,然后在您从NSURLConnectionDelegate
方法中获得内容并准备好显示撰写视图时再引用它。
保持基于委托的连接的原因可以很简单 - 基于块的版本在iOS4.3下不起作用,它在iOS5.0中引入。 – lupatus
一般来说不是一个坏的理由(至少如果你想要支持一个已经发布的应用程序; iOS 4对于新的开发来说已经很旧了)。但'SLComposeViewController'也不在iOS 4.x上,所以大概人们不必担心这种情况。 – rickster
非常优雅的解决方案rickster,我永远不会想到这个!大大清理我的代码。无关(?)但有趣的是,对于Twitter,我正在尝试从主线程中更新UI,但FaceBook工作正常。嗯。 – ToddB