Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURL add parameters to fileURLWithPath method

I use this line of code to load a local html file into a web view:

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"html"]];

However I want to add some http parameters to the url with no luck so far.

I've tried this:

url = [url URLByAppendingPathComponent:@"?param1=1"];

But after this a html doesn't load in webview.

Is there a way to load local html file in webview with params ?

like image 803
Borut Tomazin Avatar asked Aug 09 '12 11:08

Borut Tomazin


2 Answers

Do this:

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"html"]];

NSString *URLString = [url absoluteString];   
NSString *queryString = @"?param1=1"; 
NSString *URLwithQueryString = [URLString stringByAppendingString: queryString];  

NSURL *finalURL = [NSURL URLWithString:URLwithQueryString];
NSURLRequest *request = [NSURLRequest requestWithURL:finalURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:(NSTimeInterval)10.0 ];

[web loadRequest:request];
like image 90
Paresh Navadiya Avatar answered Sep 25 '22 08:09

Paresh Navadiya


The most upvoted answer by Prince doesn't always work.

In iOS 7 Apple introduced NSURLComponents class, we can leverage that to securely add a query into NSURL.

NSURL *contentURL = ...;
NSURLComponents *components = [[NSURLComponents alloc] initWithURL:contentURL resolvingAgainstBaseURL:NO];
NSMutableArray *queryItems = [components.queryItems mutableCopy];
if (!queryItems) queryItems = [[NSMutableArray alloc] init];
[queryItems addObject:[NSURLQueryItem queryItemWithName:@"access_token" value:@"token_here"]];
components.queryItems = queryItems;
NSURL *newURL = components.URL;
like image 39
Ben Lu Avatar answered Sep 21 '22 08:09

Ben Lu