Skip to content

Instantly share code, notes, and snippets.

@etolstoy
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etolstoy/adfb7bd047d7cae79211 to your computer and use it in GitHub Desktop.
Save etolstoy/adfb7bd047d7cae79211 to your computer and use it in GitHub Desktop.
IDTMessaging Test
// 4. Write a class which does HTTP request to a service in address www.idtmessaging.com and extracts the html code inside tags <head> </head> - Discuss error handling.
- (void)makeRequest {
NSString *requestUrl = @"http://www.idtmessaging.com";
NSURL *url = [NSURL URLWithString:requestUrl];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data && !connectionError) {
NSString *htmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *headString = [self obtainHeadFromHtml:htmlString];
}
}];
}
- (NSString *)obtainHeadFromHtml:(NSString *)html {
NSRegularExpression *regExp = [NSRegularExpression regularExpressionWithPattern:@"<head[^>]*>((.|[\n\r])*)</head>" options:kNilOptions error:nil];
NSTextCheckingResult *firstMatch = [regExp firstMatchInString:html options:kNilOptions range:NSMakeRange(0, html.length)];
NSString *headString = [html substringWithRange:firstMatch.range];
return headString;
}
#import <HTMLReader/HTMLReader.h>
- (NSString *)obtainHeadFromHtml:(NSString *)html {
HTMLDocument *htmlDocument = [HTMLDocument documentWithString:html];
HTMLElement *headElement = [document firstNodeMatchingSelector:@"head"];
return headElement.serializedFragment;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment