0

我无法加载任何网页。知道为什么会这样吗?webview 的框架(从调试器打印)

<UIWebView: 0x8a49840; frame = (0 0; 320 241); autoresize = TM+BM; layer = <CALayer: 0x8a498f0>>

这是我的代码:

#import "ViewController.h"

@interface ViewController () <UIWebViewDelegate>

@end

@implementation ViewController
@synthesize webview;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.webview.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidAppear:(BOOL)animated
{

}
- (IBAction)buttonPress:(id)sender {
    NSLog(@"pressed");
    NSURL *theUrl = [NSURL URLWithString:@"www.google.com"];
    NSError *e ;
    // just for test - ALSO returning nil!!!
    NSString *str =  [NSString stringWithContentsOfURL:theUrl encoding:NSUTF8StringEncoding error:&e];
    NSLog(@"%@",str);
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:theUrl];
    [self.webview loadRequest:theRequest];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"page is loading");
}
// this method is never called
-(void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"finished loading");
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}

@end
4

5 回答 5

4

用这个就行了。

problem:在您的网址http://中错过了

NSURL *theUrl = [NSURL URLWithString:@"http://www.google.com"];
于 2013-05-09T12:25:20.300 回答
1

您也可以检查您的链接是否不包含“http://”或“https://”并添加。

NSString *website = @"www.google.com";
NSRange textRangeHTTP = [[website lowercaseString] rangeOfString:@"http://"];
NSRange textRangeHTTPS = [[website lowercaseString] rangeOfString:@"https://"];
if((textRangeHTTP.location == NSNotFound) && (textRangeHTTPS.location == NSNotFound))
       website = [NSString stringWithFormat:@"http://%@",website];

NSURL *theUrl = [NSURL URLWithString:website];
于 2013-05-09T14:51:29.990 回答
1

您没有正确的网址。因为 + URLWithString: 需要一个协议(例如 http://,https://),如果你有www.google.com在这种情况下它不能建立一个 URL。所以请尝试像这样使用..

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
于 2013-05-09T12:34:14.493 回答
0

只需在您的按钮按下方法中使用它

 NSURL *theUrl = [NSURL URLWithString:@"http://www.google.com"];
 NSURLRequest *theRequest = [NSURLRequest requestWithURL:theUrl];
 [self.webview loadRequest:theRequest];

始终确保使用“http://”协议类型作为 Web url 字符串的前缀

于 2013-06-27T12:30:47.493 回答
0

(Xcode 5 iOS 7)需要更新适用于 iOS 7 和 Xcode 5 的通用应用程序。这是一个开源项目/示例,位于此处:链接到 SimpleWebView(项目 Zip 和源代码示例)

于 2014-01-12T06:31:14.800 回答