Matt Payne
Matt Payne

Reputation: 173

Loading an HTML file with URL parameters into a Cocoa (not iPhone) WebView

I'm using the following to load an HTML file into a WebView in my Mac OSX app:

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

This works fine ... but what I need to do is read that same file with some URL parameters attached to it (say foo.html?var=bar), which some JavaScript will then use for output. I tried using URLByAppendingPathExtension: on fileURL, but no dice...

Upvotes: 1

Views: 2184

Answers (2)

Rob Keniger
Rob Keniger

Reputation: 46020

The problem is that URLs created using the fileURLWithPath: method do not support query strings, as generally a query string makes no sense for a URL referencing a file on disk.

I would highly recommend you run a local web server and use http:// scheme URLs if you want to pass URL parameters to code in a web page. Relying on the WebView supporting query strings on file:// URLs is fragile, in my opinion.

That said, you can construct the URL using the URLWithString: method like this and it will work:

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

In your case you'd probably do something like:

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

Upvotes: 2

Eimantas
Eimantas

Reputation: 49354

NSString *filePath = ...
filePath = [filePath stringByAppendingFormat:@"?var=%@", @"bar"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
...

Upvotes: 0

Related Questions