简体   繁体   English

A /同步NSURLConnection:在没有下载数据的情况下获得响应?

[英]A/Synchronous NSURLConnection: get response without download data?

Help is highly appreciated. 非常感谢您的帮助。 I'm stuck here: 我被困在这里:

I need to examine a response before I start loading an URL in my UIWebView. 开始在UIWebView中加载URL之前,我需要检查响应。 However a synchronous NSURLConnection will first download the data and then let me access the response, which is bad. 但是,同步NSURLConnection将首先下载数据,然后让我访问响应,这很糟糕。

An asynchronous NSURLConnection will let me examine the response before any data is received but I only can only examine the response in the delegate method connection:didReceiveResponse: . 异步NSURLConnection可以让我在接收任何数据之前检查响应,但是我只能在委托方法connection:didReceiveResponse:中检查响应。 But then I would have to tell my webView's delegete method (webView:shouldStartLoadWithRequest:navigationType:) to wait till the the response is there. 但是然后我必须告诉我的webView的delegete方法(webView:shouldStartLoadWithRequest:navigationType :)等到响应在那里。 Because both delegates are in the main thread (do they have to be? I guess so) I can't simply use NSCondition to stop webView's delegate (cause that means stopping the main thread). 因为两个委托都在主线程中(它们一定是吗?我猜是这样),所以我不能简单地使用NSCondition来停止webView的委托(因为这意味着要停止主线程)。

Does anyone have an idea on how to solve this problem? 有谁知道如何解决这个问题?

Thanks in advance. 提前致谢。

If you just need the headers, you can first make a HEAD request (instead of a GET). 如果只需要标头,则可以首先发出HEAD请求(而不是GET)。 That will only return the headers, without any body. 那只会返回标题,没有任何正文。 That may even be fast enough that you could consider doing it synchronously, though you'd obviously want to test that thoroughly. 这甚至可能足够快,以至于您可以考虑同步执行此操作,尽管您显然希望对其进行彻底的测试。

Update 更新
Actually, don't do that synchronously. 实际上,请勿同步执行此操作。 Even with a small response size, the latency of the request alone can often be more than you want to deal with. 即使响应大小很小,仅请求的延迟通常也可能会超过您想要处理的延迟。

使用NSConnection读取所有数据,然后使用-loadData:MIMEType:textEncodingName:baseURL:将其加载到UIWebView

First, you really shouldn't be using synchronous methods for web data, the potential delays are bad. 首先,您实际上不应该对Web数据使用同步方法,因为潜在的延迟很严重。

I would suggest that you make two calls: the first to find the MIME type, which cancels the connection as soon as you can determine it. 我建议您进行两次调用:第一次调用MIME类型,这将在确定连接后立即取消连接。 The second when you want to download the full data. 要下载完整数据时的第二个。 As this might be to load into a UIWebView , this doesn't seem unreasonable. 由于这可能是加载到UIWebView ,所以这似乎并不合理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM