【问题标题】:NSURL add parameters to fileURLWithPath methodNSURL 向 fileURLWithPath 方法添加参数
【发布时间】:2012-08-06 14:59:23
【问题描述】:

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

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

但是我想在 url 中添加一些 http 参数,但到目前为止没有运气。

我试过这个:

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

但在此之后,网页视图中不会加载 html。

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

【问题讨论】:

  • 如果你NSlog添加参数后的URL是否包含它们?

标签: iphone ios parameters append nsurl


【解决方案1】:

Prince 投票最多的答案并不总是有效。

Apple 在 iOS 7 中引入了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;

【讨论】:

  • 谢谢,正是我要找的东西
  • 请注意:NSURLComponents 的 queryItems 属性仅适用于 iOS 8+
【解决方案2】:

我是这样使用的:

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

如果您的文件包含在项目导航器的资源文件夹中。否则你必须在NSString 中设置你的完整路径并在你的NSURL 路径中使用它。

【讨论】:

    【解决方案3】:

    这样做:

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

    【讨论】:

    • 这并不总是有效。如果 URL 以片段结尾(即#something),那么在运行这段代码后它就变成了一个无效的 URL。
    猜你喜欢
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多