2012-08-09 85 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