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
ユーザーがサービスを選択したときに set などを参照してくださいNSURLConnectionDelegate
メソッドからコンテンツを取得し、作成ビューを表示する準備ができたら、元に戻ります。