UIWebView无法加载本地.html文件

时间:2013-07-02 15:57:11

标签: ios uiwebview

我试图查看存储在我的Bundle中的.html文件(index.html)(在我的支持文件中)。

.html文件位于名为HTML的文件夹中。我的代码如下:

- (void)viewDidLoad
    {
     [super viewDidLoad];  

  _viewWeb.delegate = self;

    NSString *path = [[NSBundle mainBundle]
                      pathForResource:@"index" ofType:@"html" inDirectory:@"HTML"];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [_viewWeb setScalesPageToFit:YES];
    [self.viewWeb loadRequest:request];

    }

我的头文件如下所示:

@interface D6ViewController : UIViewController <UIWebViewDelegate>


    {

    IBOutlet UIWebView *viewWeb;

    }

@property (weak, nonatomic) IBOutlet UIWebView *viewWeb;

@end

我将属性合成为viewWeb = _viewWeb。持有UIWebView的viewcontroller加载正常但显示没有网页的白色屏幕。我已在IB中设置了网点。

有什么想法吗?谢谢,

5 个答案:

答案 0 :(得分:2)

您正在使用相对路径(因此是文件夹的蓝色)。您可以在Load resources from relative path using local html in uiwebview或更低版本找到此问题的答案:

将资源拖到xcode项目中,您将获得两个选项“为任何添加的文件夹创建组”和“为任何添加的文件夹创建文件夹引用”。选择“创建文件夹引用..”选项。

以下代码应该有效。

  NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"/HTML"]];
  [webView loadRequest:[NSURLRequest requestWithURL:url]];

答案 1 :(得分:1)

试试这个

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];

答案 2 :(得分:0)

在斯威夫特:

func pathForResource(name:String?,ofType ext:String?,inDirectory subpath:String?) - &gt;字符串?
   - 名称: Hmtl的名称;
   - 文件类型的 ofType ext:扩展名。在这种情况下“html”;
   - inDirectory子路径:文件夹所在的文件夹。在这种情况下,文件位于根文件夹中;

    let path = NSBundle.mainBundle().pathForResource("dados", ofType: "html", inDirectory: "root")
    var requestURL = NSURL(string:path!);
    var request = NSURLRequest(URL:requestURL);

    webView.loadRequest(request)

答案 3 :(得分:0)

你错了,这是正确的代码:

        var requestURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("index", ofType: "html", inDirectory: "www")!)
    var request = NSURLRequest(URL:requestURL!)

    myWebView.loadRequest(request)

答案 4 :(得分:0)

您可以使用此项如果您没有将HTML文件保存在任何目录中。如果要将HTML文件保存在任何目录中,请在&#34; inDirectory&#34;中指定目录名称。参数。

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"privacy-Policy" ofType:@"html" inDirectory:nil];
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
[_webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];