是否可以将哈希标记发送到UIWebView中的文件URL?

zlo*_*log 13 iphone uiwebview ios

我想从文件加载一个html页面,并为其添加一个哈希标记.这可能吗?

我试过了

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"someFile" ofType:@"html"];  
NSURL *fileUrl = [NSURL fileURLWithPath:[filePath stringByAppendingFormat:@"#hashtag"]];
[self.webView loadRequest:[NSURLRequest requestWithURL:fileUrl]];    
NSLog(@"fileUrl = %@, reachable? %d", fileUrl, [fileUrl checkResourceIsReachableAndReturnError:nil]);
Run Code Online (Sandbox Code Playgroud)

但这会尝试查找someFile.html%23hashtag无法找到的文件.有没有办法在NSURL创建对象后添加哈希?

我也尝试将文件加载到字符串中并使用loadHTMLString:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"someFile" ofType:@"html"];
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:fileContents baseURL:[NSURL URLWithString:@"http://someFile.html#hashtag"]];
Run Code Online (Sandbox Code Playgroud)

这里的哈希标签确实有效,但我在html中的javascript引用不起作用.这个方法的后续问题是,如何从UIWebView中作为字符串加载的html引用javascript文件,即什么是基本URL?

我能想到的一个黑客就是将我的所有javascript文件内联到html中并将其加载为字符串,但我认为必须有更好的方法!

Joh*_*ger 25

我没试过这个但是如何在没有hashtag的情况下正常加载文件并用这样的东西实现UIWebViewDelegate?

- (void)webViewDidFinishLoad:(UIWebView *)webView {
   [webView stringByEvaluatingJavaScriptFromString:@"window.location.href = '#hashtag';"];
}
Run Code Online (Sandbox Code Playgroud)

参考文献:

  • 这对我有用(`hash`而不是`href`):`[webView stringByEvaluatingJavaScriptFromString:@"window.location.hash ='#foo'"];` (2认同)

xia*_*ang 10

关于%23问题,我认为Scott Kohlert的替代解决方案并不好.

以下解决方案似乎更好,我只是从这里复制它

NSURL *baseUrl = [NSURL fileURLWithPath:stringUrl];
NSURL *fullURL = [NSURL URLWithString:@"#jumpto" relativeToURL:baseUrl];
Run Code Online (Sandbox Code Playgroud)

有点偏离主题,我发现iOS 6.0,6.1上的Safari与iOS 5.1和其他桌面浏览器(包括Safari for OSX)的关于带锚的句柄URL的行为有所不同.对于我的一个特定文档,无论是在UIWebview或iOS 6.0或6.1上的移动Safari中,在第一次加载时,页面都不会滚动到正确的位置,重新加载将修复它.也许它与html的一部分动态生成的事实有关.有任何想法吗?

  • 我相信这比在视图完成加载时评估javascript更好.这是目前选择的答案.这应该是正确的答案. (3认同)