如果需要委托函数,如何直接返回 NSURLConnection 加载的数据?
简短说明我想要做什么:我正在使用 NSURLConnection 连接到 SSL 网页,这是我的 API。服务器证书是自签名证书,因此您必须接受它,例如在 Web 浏览器中。我在 Stack Overflow 上找到了一个解决方案,如何解决这个问题(如何使用 NSURLConnection 与 SSL 连接以获得不受信任的证书?)
因此我添加了 NSURLConnection 委托以使用“didReceiveAuthenticationChallenge”等方法。因此,我无法使用它:
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
因为在这种情况下不可能使用委托函数。我的问题如下:我需要一个如下所示的函数:
- (NSDictionary *)getData : (NSArray *)parameter {
[...|
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[...]
return myDictionary;
}
如何使用它返回 NSDictionary?据您所知,现在调用 NSURLConnection 的委托函数,并且此时响应不可用。问题是视图控制器依赖于这个响应,所以我需要直接返回字典...有人知道这个问题的解决方案吗?回调函数怎么样?
A short explanation what I want to do: I'm using NSURLConnection to connect to a SSL webpage which is my API. The servers certificate is a self signed one so you have to accept it, for example in a web browser. I've found a solution on Stack Overflow how to do the trick (How to use NSURLConnection to connect with SSL for an untrusted cert?)
So I've added the NSURLConnection delegate to use methods like "didReceiveAuthenticationChallenge". As a result of that I cannot use this:
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
because there is no possibility to use the delegate functions in this case. My question is the following: I need a function which looks like this:
- (NSDictionary *)getData : (NSArray *)parameter {
[...|
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[...]
return myDictionary;
}
how can I return a NSDictionary by using this? As far as you know the delegate function of NSURLConnection are called now and the response isn't available at this point. The problem is that the view controller depends on this response so I need to return the dictionary directly... Does anybody know a solution for this? What about a callback function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,我已经找到了解决方案。在 Objective-C 中使用块是一件非常好的事情。
首先,您必须向 NSURLRequest 和 NSURL 添加一些方法:
而不仅仅是实现以下类:
现在您可以执行以下某种回调函数:
在这里您可以找到 ICNH 的原始德语解决方案: 异步 I/O mit Bloecken
非常感谢您!
okay, I've found a solution for that. A very good thing is to use blocks in objective-c.
First of all you have to add some methods to NSURLRequest and NSURL:
And than just implement the follwing class:
Now you can do the follwing, some kind of callback function:
Here you can find the orginal german solution by ICNH: Asynchrones I/O mit Bloecken
Thank you very much for this!
我的建议是对 NSURLConnection 使用一些其他委托方法,例如
connection:didReceiveResponse:
或connection:didReceiveData:
。您可能应该像这样保留使用设置:My suggestion would be to use some other delegate methods for NSURLConnection like
connection:didReceiveResponse:
orconnection:didReceiveData:
. You should probably keep a use a set up like so: