1

我正在使用NSURLConnection从响应中加载数据。它可以正常工作,委托方法 connectionDidFinishLoading 具有我需要的数据的连接实例。问题是我想在请求中传递一些信息,以便在连接完成加载时可以获得它:

  1. 用户希望通过(Facebook、Twitter、C、D)共享 URL 的内容。
  2. NSURLConnection用于获取URL的内容
  3. 获得内容后,我使用 SL 框架 SLComposeViewController:composeViewControllerForServiceType并需要为其指定服务类型
  4. 此时我不知道用户在步骤 1 中选择了什么服务。我想用NSURLConnection.

我可以NSURLConnection为此扩展一个属性吗?这似乎非常严厉。必须有一个“正确的方法”来做到这一点。

非常感谢

4

2 回答 2

4

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方法中获取内容并准备好显示撰写视图后,请返回它。

于 2013-01-18T21:44:06.080 回答
1

您可以检查实例的URL属性NSURLConnection并通过解析baseURLor的absoluteString属性来确定服务,URL例如- (ServiceType)serviceTypeForURL:(NSURL *)theURL;

所有的NSURLConnectionDelegate方法都传递调用NSURLConnection对象——所以你可以从

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

或者

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

于 2013-01-18T21:22:42.703 回答