iOS:WebView加载网址

时间:2012-10-08 19:08:26

标签: ios xcode url uiwebview

我正在尝试在UIWebView中打开以下网址,但无法加载,而是将其更改为:

 http://www.google.com

工作正常。

我要加载的网址是:

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@%@%@",@"http://m.forrent.com/search.php?address=",[[bookListing objectForKey:@"Data"] objectForKey:@"zip"],@"&beds=&baths=&price_to=0#{\"lat\":\"0\",\"lon\":\"0\",\"distance\":\"25\",\"seed\":\"1622727896\",\"is_sort_default\":\"1\",\"sort_by\":\"\",\"page\":\"1\",\"startIndex\":\"0\",\"address\":\"",[[bookListing objectForKey:@"Data"] objectForKey:@"zip"],@"\",\"beds\":\"\",\"baths\":\"\",\"price_to\":\"0\"}"]]]];

更新:

我故意逃过双引号,否则它会给我一个错误。 我在浏览器中打开(在笔记本电脑上)检查了网址,它的效果非常好:

浏览器中的网址:

http://m.forrent.com/search.php?address=92115&beds=&baths=&price_to=0#{%22lat%22:%220%22,%22lon%22:%220%22,%22distance%22:%2225%22,%22seed%22:%221622727896%22,%22is_sort_default%22:%221%22,%22sort_by%22:%22%22,%22page%22:%221%22,%22startIndex%22:%220%22,%22address%22:%2292115%22,%22beds%22:%22%22,%22baths%22:%22%22,%22price_to%22:%220%22}

2 个答案:

答案 0 :(得分:20)

您的代码行看起来很复杂,但基本上它是一个非常简单的代码。

您应该将此代码从一行内容拆分为多行,这些行更具可读性。 这也将允许您记录并检查您实际创建的URL,如下所示:

NSLog(@"My url: %@", urlString);

更新: 我看到你添加了完整的网址。 Webview确实无法加载该URL(UIWebkit错误101)。

导致问题的url部分是params后面的'#'字符和字典。你应该url编码网址的那一部分。

试试这个:

NSString *address = @"http://m.forrent.com/search.php?";
NSString *params1 = @"address=92115&beds=&baths=&price_to=0";

// URL encode the problematic part of the url.
NSString *params2 = @"#{%22lat%22:%220%22,%22lon%22:%220%22,%22distance%22:%2225%22,%22seed%22:%221622727896%22,%22is_sort_default%22:%221%22,%22sort_by%22:%22%22,%22page%22:%221%22,%22startIndex%22:%220%22,%22address%22:%2292115%22,%22beds%22:%22%22,%22baths%22:%22%22,%22price_to%22:%220%22}";
params2 = [self escape:params2];

// Build the url and loadRequest
NSString *urlString = [NSString stringWithFormat:@"%@%@%@",address,params1,params2];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];

我使用的转义方法:

- (NSString *)escape:(NSString *)text
{
    return (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                        (__bridge CFStringRef)text, NULL,
                                                                        (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                        kCFStringEncodingUTF8);
}

答案 1 :(得分:1)

我会尝试对您网址中的所有键/值项进行编码。具体来说,花括号({})和散列(#)符号可能会导致问题。