【问题标题】:How to get the http response for NSURLConnection without using delegates如何在不使用委托的情况下获取 NSURLConnection 的 http 响应
【发布时间】:2013-08-25 11:40:40
【问题描述】:

我想知道是否有一种方法可以在不使用 Apple 提供的委托的情况下获取 NSURLConnection 的 HTTP 响应。

例如,如果我以以下方式设置连接:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"player.UpdateProfile" forHTTPHeaderField:@"player-profile"];
[self addHttpHeaders:request];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately: YES];

现在这里不是委托给self 并在didReceiveResponse 方法中解析响应,我可以创建一个自定义委托来解析响应吗?我不需要关于如何做到这一点的完整教程,但我们将不胜感激。谢谢

【问题讨论】:

  • 是的,您可以将委托设置为您希望的任何对象,只要该对象符合委托定义的协议。
  • 在 Github 上查看 AFNetworking (github.com/AFNetworking/AFNetworking)。这是一个非常令人难以置信的库,它封装了此功能并使其非常易于使用。
  • “自定义委托”是什么意思?请解释一下。

标签: ios nsurlconnection nsurlrequest nsurlconnectiondelegate


【解决方案1】:

NSURLConnection 现在可能更容易使用:

[NSURLConnection sendAsynchronousRequest: urlRequest
                                   queue: [NSOperationQueue mainQueue]
                       completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error)
{
}

这完全避免了创建任何委托对象。请注意:取消此类请求非常困难,因此请确保在响应处理程序中设置保护措施。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多