编辑:刚刚看到你找到了答案...... sheeeiiittt
我真的只是学到了这个!为此,您甚至不需要将其显示在 UIWebView 中。(但是当你使用它时,你可以获取当前页面的 URL)
无论如何,这是代码和一些(微弱的)解释:
//create a URL which for the site you want to get the info from.. just replace google with whatever you want
NSURL *currentURL = [NSURL URLWithString:@"http://www.google.com"];
//for any exceptions/errors
NSError *error;
//converts the url html to a string
NSString *htmlCode = [NSString stringWithContentsOfURL:currentURL encoding:NSASCIIStringEncoding error:&error];
所以我们有了 HTML 代码,现在我们如何获得标题?好吧,在每个基于 html 的文档中,标题都由 This Is the Title 发出信号 所以可能最简单的方法是在 htmlCode 字符串中搜索 , 和 for ,然后将其子串化,以便我们得到介于两者之间的内容。
//so let's create two strings that are our starting and ending signs
NSString *startPoint = @"<title>";
NSString *endPoint = @"</title>";
//now in substringing in obj-c they're mostly based off of ranges, so we need to make some ranges
NSRange startRange = [htmlCode rangeOfString:startPoint];
NSRange endRange = [htmlCode rangeOfString:endPoint];
//so what this is doing is it is finding the location in the html code and turning it
//into two ints: the location and the length of the string
//once we have this, we can do the substringing!
//so just for easiness, let's make another string to have the title in
NSString *docTitle = [htmlString substringWithRange:NSMakeRange(startRange.location + startRange.length, endRange.location)];
NSLog(@"%@", docTitle);
//just to print it out and see it's right
就是这样!所以基本上要解释 docTitle 中发生的所有恶作剧,如果我们只是通过说 NSMakeRange(startRange.location, endRange.location) 来创建一个范围,我们将获得 startString 的标题和文本(即 ),因为位置是字符串的第一个字符。所以为了抵消它,我们只是添加了字符串的长度
现在请记住,此代码未经测试。如果有任何问题,可能是拼写错误,或者我没有/确实在不应该添加指针时添加了指针。
如果标题有点奇怪且不完全正确,请尝试使用 NSMakeRange ——我的意思是添加/减去字符串的不同长度/位置——任何看起来合乎逻辑的东西。
如果您有任何疑问或有任何问题,请随时提出。这是我在这个网站上的第一个答案,如果有点混乱,很抱歉