2012-08-09 86 views
11

我用这行代码到本地的HTML文件加载到Web视图:NSURL参数添加到fileURLWithPath方法

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

但是我想一些HTTP参数没有运气添加到URL为止。

我已经试过这样:

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

但经过这一个html不会在web视图加载。

有没有办法使用params在webview中加载本地html文件?

+0

如果您在添加参数后添加了“NSlog”URL,那么它们包含在内? – rckoenes 2012-08-09 11:41:50

回答

13

这样做:

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]; 
+0

就是这样。谢谢! – 2012-08-09 12:08:38

+1

这个答案我需要+50票投票按钮。 – DataGraham 2012-09-18 15:58:36

+0

这并不总是有效。如果URL以片段结尾(即#something),那么在运行这段代码后,它将变为无效的URL。 – 2015-06-09 00:37:25

1

我使用这样的方法:

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

如果你的文件包含到Project Navigator的资源文件夹中。否则,您必须在NSString中设置完整路径,并在NSURL路径中使用该路径。

6

王子并不总是工作的最高的答案。

在iOS 7中Apple引入了NSURLComponents类,我们可以利用它来安全地将查询添加到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; 
+0

谢谢,我一直在寻找 – 2015-11-20 16:17:26

+0

这里有一点需要注意:NSURLComponents的queryItems属性仅适用于iOS 8+ – 2015-11-20 16:27:32