Objective c 将带有URL参数的HTML文件加载到Cocoa(不是iPhone)网络视图中

Objective c 将带有URL参数的HTML文件加载到Cocoa(不是iPhone)网络视图中,objective-c,macos,cocoa,url,webview,Objective C,Macos,Cocoa,Url,Webview,我使用以下方法将HTML文件加载到Mac OSX应用程序的WebView中: NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"html"]; NSURL *fileURL = [NSURL fileURLWithPath:filePath]; NSURLRequest *request = [NSURLRequest requestWithURL:fileURL]; [[WebView mai

我使用以下方法将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上附加路径扩展名:来使用
URL,但没有骰子…

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

NSString *filePath = ...
filePath = [filePath stringByAppendingFormat:@"?var=%@", @"bar"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
...
我强烈建议您运行本地web服务器,并使用
http://
scheme URL,如果您希望将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
后的行上的code>。日志显示我想要的URL、参数和所有。。。但只加载了一个空白页……也许我在别处出错了。我使用的完整代码块是:`NSString*filePath=[[NSBundle mainBundle]pathForResource:@“foo”of type:@“html”];NSString*URLString=[NSString stringWithFormat:@]file://localhost%@?var=%@,文件路径,@“条”]//NSLog(URLString);NSURL*文件URL=[NSURL URLWithString:URLString];NSURLRequest*request=[nsurlRequestRequestWithURL:fileURL];[[webView大型机]加载请求:请求]`