Yllier
Yllier

Reputation: 197

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. However a synchronous NSURLConnection will first download the data and then let me access the response, which is bad.

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: . But then I would have to tell my webView's delegete method (webView:shouldStartLoadWithRequest:navigationType:) to wait till the the response is there. 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).

Does anyone have an idea on how to solve this problem?

Thanks in advance.

Upvotes: 2

Views: 2217

Answers (3)

BJ Homer
BJ Homer

Reputation: 49034

If you just need the headers, you can first make a HEAD request (instead of a 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.

Upvotes: 4

Paul Lynch
Paul Lynch

Reputation: 19789

First, you really shouldn't be using synchronous methods for web data, the potential delays are bad.

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. The second when you want to download the full data. As this might be to load into a UIWebView, this doesn't seem unreasonable.

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299355

Read all the data using NSConnection, then load it into the UIWebView using -loadData:MIMEType:textEncodingName:baseURL:.

Upvotes: 1

Related Questions