Re: Asynchronous downloading and parsing of XML
Re: Asynchronous downloading and parsing of XML
- Subject: Re: Asynchronous downloading and parsing of XML
- From: Thomas Davie <email@hidden>
- Date: Sat, 06 Aug 2011 21:08:13 +0100
Just for reference, With the help of Mike Ash I figured out how to do this sensibly. Note, code typed straight into Mail.app, so it may not be dead perfect, but it should show the idea:
//When creating the NSURLConnection and parser:
- (void)doMagicParsingStuff
{
NSInputStream *iStream;
NSOutputStream *oStream;
CFStreamCreateBoundPair(NULL, &iStream, &oStream, 4096);
[oStream setDelegate:self];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[iStream scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
finishedLoading = NO;
[iStream open];
[oStream open];
[self setParserStream:oStream];
NSXMLParser *parser = [[[NSXMLParser alloc] initWithStream:iStream] autorelease];
}
- (void)attemptToWriteToStream
{
NSUInteger written = [[self parserStream] writeBytes:[[self buffer] bytes] maxLength:[[self buffer] length]];
[[self buffer] replaceBytesInRange:NSMakeRange(0,written) withBytes:"" length:0];
}
// In the output stream delegate:
- (void)stream:(NSStream *)s handleEvent:(NSStreamEvent)event
{
if (NSStreamEventHasSpaceAvailable == event)
{
if (finishedLoading && [[self buffer] length] == 0)
{
[[self parserStream] close];
}
else
{
[self attepmtToWriteToStream];
}
}
}
// In the NSURLConnection Delegate:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d
{
[[self buffer] appendData:d];
[self attemptToWriteToStream];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
finishedLoading = YES;
}
On 6 Aug 2011, at 12:14, Mikkel Islay wrote:
> You can't hook up NSURLConnection to NSXMLParser like that because it loads its data asynchronously. Rather, feed it (a copy of) the NSData object generated by NSURLConnection, or bypass NSURLConnection completely and load your data via NSInputStream. In either case you will have to verify that the data you feed to NSXMLParser is complete.
>
> Mikkel
>
> On 6 Aug 2011, at 12:02, Thomas Davie wrote:
>
>>
>> I'm trying to figure out how to download and parse XML at the same time. NSXMLParser seems to have support for this by providing it with an NSInputStream. However, I see no way to get an NSInputStream that contains the data that an NSURLConnection is downloading.
>
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden