Today I needed to load a local html file into a UIWebView and jump to a specific section in the file. I thought this is simple enough all I have to do before creating a NSURL is make sure the url string has the correct anchor appended at the end of it. So I tried:
View CodeOBJC | |
UIWebView *myWebView = [[UIWebView alloc] initWithFrame:frame]; NSBundle *mainBundle = [NSBundle mainBundle]; NSString *stringUrl = [mainBundle pathForResource:@"mypage" ofType:@"html"]; stringUrl = [stringUrl stringByAppendingString:@"#jumpto"]; NSURL *baseUrl = [NSURL fileURLWithPath:stringUrl]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL:baseUrl]; [myWebView loadRequest:urlRequest]; | |
Unfortunately it turns out that [NSURL fileURLWithPath:stringUrl]; encodes the string converting the # symbol into %23 escape code, which prevents the page from loading. Finally I found the solution by first creating a NSURL variable and then appending the anchor link to it. Here is the code that got the job done:
View CodeOBJC | |
UIWebView *myWebView = [[UIWebView alloc] initWithFrame:frame]; NSBundle *mainBundle = [NSBundle mainBundle]; NSString *stringUrl = [mainBundle pathForResource:@"mypage" ofType:@"html"]; NSURL *baseUrl = [NSURL fileURLWithPath:stringUrl]; NSURL *fullURL = [NSURL URLWithString:@"#jumpto" relativeToURL:baseUrl]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL:fullURL]; [myWebView loadRequest:urlRequest]; | |