我有一个非常简单的iOS应用程序,带有一个uiwebview,加载一个非常简单的测试页面(test.html):

<html>
<body>
<img src="img/myimage.png" />
</body>
</html>

我加载这个测试.将html文件导入我的web视图:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
NSString *html = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[webView loadHTMLString:html baseURL:baseUrl];

This works fine if I reference the image without the relative path and put the referenced image in the root path under Targets -> Copy Bundle Resources within XCode, however I can't get it to work with the relative path as shown in my html file. There must be a way to do this, I have lots of images, css, javascript files that I want to load into the webview and I would like not to have to have everything in the root and have to change all the references in my web app.

推荐答案

这就是如何加载/使用具有相对引用的本地html.

  1. 将资源拖到您的Xcode项目中(我从我的finder窗口中拖动了一个名为www的文件夹),您将看到两个选项"create group for any addited Folders"和"create folders reference for any addited Folders"(为任何添加的文件夹创建文件夹引用).
  2. Select "创建文件夹引用.."选项.
  3. 使用下面给出的代码.它应该很有魅力.

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

现在,html中的所有相关链接(如img/.gif, js/.js)都应该得到解析.

Swift 3

    if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
        webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
    }

Ios相关问答推荐

如何使用UICollectionView Compositionallayout在UIKit中正确渲染远程图像

如何在SWIFT中处理不可发送的类型?

设置堆栈视图的所有属性

如何在 Swift 中存储具有关联值的协议?

SwiftUI 动画:为什么容器视图在移动?我很难理解这种行为

Swift Combine 防止初始值触发接收器并同时防止重复?

我正在try 制作一种 Select 器样式,例如设置中的外观 Select 器

如何在Collection 后更改并保留按钮 colored颜色 ,然后在 SwiftUI 中切换回来?

Swiftui为什么在点击第二行之前背景不起作用

TextField 重复输入 SwiftUI

无法结合 UIImageView 旋转动画和 tableView 部分重新加载

Apple Push Service 证书不受信任

Xcode - 错误 ITMS-90635 - Bundle 包中的 Mach-O 无效 - 提交到 App Store

Xcode 项目格式:3.1、3.2、6.3 和 8.0 有什么区别?

如何启用滑动以删除 TableView 中的单元格?

@IBDesignable 崩溃代理

什么是伞头?

Swift - 获取设备的 WIFI IP 地址

有没有办法在应用store 之外分发 ios 应用程序?

如何在 iphone 屏幕中间显示活动指示器?