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,您始终可以使用 ivar 或附加到处理此过程的任何对象的其他一些状态:self.serviceType
当用户选择服务时设置或类似的,然后参考从NSURLConnectionDelegate
方法中获取内容并准备好显示撰写视图后,请返回它。