我知道使用UIWebview
可以在委托方法webViewDidFinishLoad
但是,我想知道是否有办法只在没有加载整个网页的情况下获得标题?喜欢http请求还是别的什么?
答案 0 :(得分:0)
这可以这样做,例如:
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
^(NSURLResponse *response, NSData *data, NSError *err) {
// Get Title
NSString *strTitle = @"";
if (data && !err)
{
NSString *returnDataIntoString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(@"data : %@",returnDataIntoString);
if (returnDataIntoString.length > 0)
{
NSError *error = nil;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithHTMLString:returnDataIntoString encoding:NSUTF8StringEncoding error:&error];
if (doc && !error) {
NSArray *employees = [doc nodesForXPath:@"//title" error:NULL];
for (GDataXMLElement *employe in employees) {
strTitle = [employe stringValue];
}
}
}
}
else
{
NSLog(@"Error : %@",[err description]);
}
//Set Title here
}];
答案 1 :(得分:0)
你有一个完整的HTML字符串吗?如果有的话,可以使用正则表达式解析字符串:
NSString *string = @"Your HTML String";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"<title[^>]*>(.*?)</title>"
options:0
error:&error];
NSTextCheckingResult *result = [regex firstMatchInString:string options:NSMatchingReportProgress range:NSMakeRange(0, [string length])];
NSRange titleRange = [result rangeAtIndex:1];
NSString *title = [string substringWithRange:titleRange];