代码之家  ›  专栏  ›  技术社区  ›  Borut Tomazin

NSURL将参数添加到文件URLWithPath方法

  •  12
  • Borut Tomazin  · 技术社区  · 14 年前

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

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

    然而,我想在url中添加一些http参数,但到目前为止还没有成功。

    我试过了:

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

    但在这之后,html就不会加载到webview中。

    有没有一种方法可以用params在webview中加载本地html文件?

    3 回复  |  直到 14 年前
        1
  •  13
  •   Paresh Navadiya    14 年前

    请执行以下操作:

    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];
    
        2
  •  6
  •   Ben Lu    11 年前

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

    在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;
    
        3
  •  1
  •   Senthilkumar    14 年前

    我这样使用:

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

    如果您的文件包含在项目导航器的Resource文件夹中。否则,您必须设置完整的路径 NSString 并将其用于 NSURL 路径

    推荐文章