uiwebview 获取html,如何获取UIWebView中显示的HTML页面的标题?

Edit: just saw you found out the answer... sheeeiiitttt

I literally just learned this! To do this, you don't even need to have it displayed in UIWebView. (But as you are using it, you can just get the URL of the current page)

Anyways, here's the code and some (feeble) explanation:

//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];

So we have the HTML code, now how do we get the title? Well, in every html-based doc the title is signaled by This Is the Title

So probably the easiest thing to do is to search that htmlCode string for , and for , and substring it so we get the stuff in between.

//so let's create two strings that are our starting and ending signs

NSString *startPoint = @"

";

NSString *endPoint = @"

";

//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

And that's really it!

So basically to explain all the shenanigans going on in the docTitle, if we made a range just by saying NSMakeRange(startRange.location, endRange.location) we would get the title AND the text of startString (which is ) because the location is by the first character of the string.

So in order to offset that, we just added the length of the string

Now keep in mind this code is not tested.. if there are any problems it might be a spelling error, or that I didn't/did add a pointer when i wasn't supposed to.

If the title is a little weird and not completely right, try messing around with the NSMakeRange-- I mean like add/subtract different lengths/locations of the strings --- anything that seems logical.

If you have any questions or there are any problems, feel free to ask. This my first answer on this website so sorry if it's a little disorganized

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值