【问题标题】:Loading an HTML file with URL parameters into a Cocoa (not iPhone) WebView将带有 URL 参数的 HTML 文件加载到 Cocoa(不是 iPhone)WebView 中
【发布时间】:2012-04-24 17:32:43
【问题描述】:

我正在使用以下内容将 HTML 文件加载到我的 Mac OSX 应用程序中的 WebView 中:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"html"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
[[WebView mainFrame] loadRequest:request];

这很好用......但我需要做的是读取同一个文件,并附加一些 URL 参数(比如foo.html?var=bar),然后一些 JavaScript 将使用这些参数进行输出。我尝试在 fileURL 上使用URLByAppendingPathExtension:,但没有骰子...

【问题讨论】:

    标签: objective-c macos cocoa url webview


    【解决方案1】:

    问题是使用 fileURLWithPath: 方法创建的 URL 不支持查询字符串,因为通常查询字符串对于引用磁盘上文件的 URL 没有意义。

    如果您想将 URL 参数传递给网页中的代码,我强烈建议您运行本地 Web 服务器并使用 http:// 方案 URL。在我看来,依靠WebView 支持file:// URL 上的查询字符串是脆弱的。

    也就是说,您可以像这样使用 URLWithString: 方法构造 URL,它会起作用:

    NSURL* fileURL = [NSURL URLWithString:@"file://localhost/Users/you/Desktop/foo.html?bar=foobar"];
    

    在您的情况下,您可能会执行以下操作:

    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"html"];
    NSString* URLString = [NSString stringWithFormat:@"file://localhost%@?var=%@", filePath, @"bar"];
    NSURL* fileURL = [NSURL URLWithString:URLString];
    

    【讨论】:

    • 抱歉,第二行有错字。固定的。当您在浏览器中编写代码时会发生这种情况!
    • 这应该没什么区别。尝试记录URLString。你得到了什么?
    • NSLog(@"%@", URLString); 在声明URLString 之后的行。
    • 日志显示了我想要的 URL、参数和所有...但是除了加载一个空白页面之外什么都没有...
    • 也许我在别处犯了错误。我正在使用的完整代码块是:` NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"html"]; NSString *URLString = [NSString stringWithFormat:@"file://localhost%@?var=%@",filePath,@"bar"]; //NSLog(URLString); NSURL *fileURL = [NSURL URLWithString:URLString]; NSURLRequest *request = [NSURLRequest requestWithURL:fileURL]; [[webView mainFrame] loadRequest:request];`
    【解决方案2】:
    NSString *filePath = ...
    filePath = [filePath stringByAppendingFormat:@"?var=%@", @"bar"];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 2018-04-28
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多