UIWebView未加载视图

时间:2014-03-25 21:52:29

标签: ios objective-c uiwebview

我的UIWebView似乎没有加载:

- (void)viewDidAppear:(BOOL)animated {

[super viewDidAppear:animated];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *urlAddress = [defaults stringForKey:@"webPage"];
NSLog(@"%@", urlAddress);

NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:urlAddress]];
webView.delegate = self;
[webView loadRequest:requestObj];

}

它位于UIViewController(通过IB连接),urlAddress返回google.com

3 个答案:

答案 0 :(得分:0)

您可以检查提取的网址是否有效吗?

    NSString *urlAddress = [defaults stringForKey:@"webPage"];
    NSLog(@"%@", urlAddress);
    NSURL *u = [NSURL URLWithString:urlAddress];
    if(u){
      NSURLRequest *requestObj = [NSURLRequest requestWithURL:u];
      webView.delegate = self;
      [webView loadRequest:requestObj];
    }else{
      [[[UIAlertView alloc] initWithTitle:@"" message:@"invalid url." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
    }

google.com不是有效的网址,应该是http://www.google.com。所以也许这就是问题所在。

答案 1 :(得分:0)

试试这段代码:

    - (void)viewDidAppear:(BOOL)animated 
    {
        [super viewDidAppear:animated];
        webView.delegate = self;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *urlAddress = [defaults stringForKey:@"webPage"];
        NSLog(@"%@", urlAddress);
        [self openURLFromString:urlAddress];
    }

    - (void) openURLFromString:(NSString*) urlString
    {
        NSURL *url = [self validateAddress:urlString];
        NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
        [webView loadRequest:request];
    }

    - (NSURL*) validateAddress:(NSString*) address
    {
        NSURL* result = [NSURL URLWithString:address];
        if (!result.scheme)
        {
            NSString* modifiedURLString = [NSString stringWithFormat:@"http://%@", address];
            result = [NSURL URLWithString:modifiedURLString];
        }

        return result;
    }

    #pragma mark - UIWebViewDelegate
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSMutableURLRequest *)urlRequest navigationType:(UIWebViewNavigationType)navigationType
    {
        return YES;
    }

答案 2 :(得分:0)

您遗漏了基本网址部分网址(Click here to read more about this),这是必要的。

所以试试这个:

- (void)viewDidAppear:(BOOL)animated {

[super viewDidAppear:animated];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *urlAddress = [defaults stringForKey:@"webPage"];
NSString * theURL = [NSString stringWithFormat:@"http://%@", urlAddress]; // you can also use stringByAppendingString if you prefer
NSLog(@"%@", theURL);

NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:theURL]];
webView.delegate = self;
[webView loadRequest:requestObj];

}

HTH:)