Re: Loading contents of URL in a string
Re: Loading contents of URL in a string
- Subject: Re: Loading contents of URL in a string
- From: Nicko van Someren <email@hidden>
- Date: Thu, 8 Dec 2005 13:02:41 +0000
On 8 Dec 2005, at 05:32, Tito Ciuro wrote:
I'm trying to load the contents of a web page into an NSString for
further processing. I've tried several things, which sort of work,
but not entirely. I've tried something like this:
NSString *string = @"http://...";
NSURL *url = [NSURL URLWithString:string];
NSData *data = [url resourceDataUsingCache:NO];
NSString *urlContents = [[[NSString alloc]initWithData:data
encoding:NSASCIIStringEncoding]autorelease];
NSString *otherURLContents = [NSString stringWithContentsOfURL:url];
If I use something like "http://www.apple.com", no problem: both
urlContents and otherURLContents show the HTML source. However, if
I specify something like "http://wwwa.accuweather.com/index-
forecast.asp?partner=accuweather&myadc=0&zipcode=94025&u=1", the
contents show up in this form:
\u008b\u00ed\u00bd`I\u0096
...
This is a big fat unfixed bug in Apple's Foundation framework. If
you use any of the -initWithContentsOfURL: methods in these classes,
or their equivalent +<foo>WithContentsOfURL: messages, or you use -
resourceDataUsingCache: then the HTTP loader sends a header line
explicitly requesting transport compression of the data but then does
not decompress the data if it gets compressed in transit.
The simplest word-around that I've found is to get a URL handle for
the URL and then fetch the resource data from there, which is to say
rather than doing:
NSData *data = [url resourceDataUsingCache:NO]; // This is broken
if the server supports compression
You should instead do:
NSData *data = [[url URLHandleUsingCache:NO] resourceData]; // This
works even if the server handles compression
Clearly there is no justification for these two behaving differently,
hence my assertion that this is a bug rather than a feature (as was
once claimed by a now-departed member of Apple staff on this list).
A quick check with the AccuWeather URL you gave shows that the former
fails and the later works as expected.
Cheers,
Nicko
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden