NSURL向fileURLWithPath方法添加参数

Bor*_*zin 11 iphone parameters append nsurl ios

我使用这行代码将本地html文件加载到Web视图中:

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"html"]];
Run Code Online (Sandbox Code Playgroud)

但是我想在网址上添加一些http参数到目前为止没有运气.

我试过这个:

url = [url URLByAppendingPathComponent:@"?param1=1"];
Run Code Online (Sandbox Code Playgroud)

但在此之后,html不会加载到webview中.

有没有办法在paraview中加载webview中的本地html文件?

Par*_*iya 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];
Run Code Online (Sandbox Code Playgroud)


Ben*_* Lu 6

通过最upvoted答案王子并不总是奏效.

在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;
Run Code Online (Sandbox Code Playgroud)