Skip to content

Instantly share code, notes, and snippets.

@jonsterling
Created June 11, 2010 08:35
Show Gist options
  • Select an option

  • Save jonsterling/434247 to your computer and use it in GitHub Desktop.

Select an option

Save jonsterling/434247 to your computer and use it in GitHub Desktop.
/* NOTES:
Fun use of a higher-order-block and some maybe objects.
*/
- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock {
Function (^blockForEncoding)(NSStringEncoding) = ^Function (NSStringEncoding enc) {
return [^(id d) { return [[[NSString alloc] initWithData:d encoding:enc] autorelease]; } copyrelease];
};
id utf8Str = [[FKMaybe return:CDATABlock] map:blockForEncoding(NSUTF8StringEncoding)];
id latin1Str = [[FKMaybe return:CDATABlock] map:blockForEncoding(NSISOLatin1StringEncoding)];
[[utf8Str orElse:latin1Str] foreach:^(id str) {
[self.currentText appendString:str];
NSLog(@"result: %@", str);
}];
}
/* NOTES:
-[JSFeedParser startConnection] starts the chain of events that results in a feed
being downloaded and parsed. But if the connection cannot be made in the very
beginning, it's useful to know about that's why I've tried to wrap as many
of my action methods in JSFeedParser in FKEither. That way, I can NSLog
the return value of any message and see if it failed or succeeded. In fact, if
these methods are invoked from within each other (a perfect tree of invocations)
the return value of the last method to be called will be either its Right value
or the value of the first error to occur in the chain. Hence, you can linearly
fix bugs in your pipeline. How cool is that?
*/
- (FKEither *)startConnection {
[self reset];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:self.feedURL
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:180] autorelease];
[request setValue:NSStringFromClass([self class]) forHTTPHeaderField:@"User-Agent"];
self.connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
return [[[FKEither return:self] bind:^(id s) {
id err = [NSString stringWithFormat:@"Asynchronous connection failed to URL %@",
self.feedURL.absoluteString];
return [FKEither right:self.connection orLeft:err];
}] foreach:^(id c) {
self.asynchronousData = [[NSMutableData new] autorelease];
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment