繁体   English   中英

iOS UIWebView在NSURLConnection之后无法加载url

[英]iOS UIWebView not load url after NSURLConnection

使用iOS 7 SDK创建简单的应用程序,但在ios 6.x和7.x上测试应用程序,结果相同。 有两个ViewController –第一个MainScreen和第二个WebScreen

如果我在MainScreen上的URL上使用NSURLConnection,则UIWebView不会从同一站点加载内容。

在主屏幕中,我将json作为字符串从url加载

NSString *urlAsString = [NSString stringWithFormat:@"https://site.ws/api/index/index?method=get_count_new_orders&login=%@&password=%@", @"login", @"pass"];
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:url] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

        if (error) {
            NSLog(@"error ::: %@", error);
        } else {

            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

            NSError *jserror = nil;            
            NSDictionary *JSON = nil;
            JSON = [NSJSONSerialization JSONObjectWithData: [string dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &jserror];

        }

    }];

在第二个屏幕上,我尝试从同一站点加载页面:

NSString *stringUrl = [NSString stringWithFormat:@"https://reserva.ws/?lang=en"];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:stringUrl]]];

和UIWebView加载空白页。

但是,如果我在第一个屏幕上评论[NSURLConnection sendAsynchronousRequest ...,则webview可以正常工作。

我对您的问题进行了小型研究,然后将您的代码复制到Xcode。 我所做的是:

  1. 基于UINavigationController创建新项目。
  2. 在root vc中,我将第一个代码示例复制到viewDidLoad方法。
  3. 在第二个vc中,我将第二个代码示例复制到viewDidLoad方法。
  4. 在vc之间切换是基于从/到UINavigationController堆栈的pop / push vc。
  5. 最后,一切看起来都很好。

推送第二个vc webview之后,正确加载url源网页。 我认为您应该使用webview委托属性并将其设置为您的webview对象所在的vc。 然后在其中实现此vc方法:

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)错误

并检查是否收到错误,以防您的Web视图未加载。 它应该可以帮助您找到问题的根源。

经过几天的考虑,我认为这可能是由于Cookie所致。 我尝试[self.webView loadRequest ...

NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
    [storage deleteCookie:cookie];
}

而这个修复问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM