这是我的代码:
var fileContent = ""
let baseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = baseURL.appendingPathComponent("index").appendingPathExtension("html")
do {
fileContent = try String(contentsOf: fileURL, encoding: String.Encoding.utf8)
} catch let error as NSError {
print("Failed getting content of the file: \(fileURL), Error: " + error.localizedDescription)
fileContent = ""
}
editorWebView!.loadHTMLString(fileContent, baseURL: baseURL)
问题是:
<img src='resources/check-box-uncheck.png'>
WKWebView加载html字符串但不显示图像。我使用FileManager复制了documentDirectory中的index.html文件和相关文件。我不想使用mainBundle。 请帮忙吗?
baseURL是: 文件:/// VAR /移动/容器/数据/应用/ C89D5B66-30FD-4B88-949F-F591E0EA1BE7 /文档/
检查文件和文件夹的功能: func allFilesList(atPath:URL) - &gt; [串]? {
var allFileNames = [String]()
do {
let fullPaths = try self.contentsOfDirectory(at: atPath, includingPropertiesForKeys:[], options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
for fileName in fullPaths {
let theFileName = fileName.lastPathComponent
allFileNames.append(theFileName)
}
} catch let error {
print("Error for list folders OR notes: \(error.localizedDescription)")
}
return allFileNames
}
答案 0 :(得分:0)
我在代码中发现了这个错误。我没有附加要复制的文件。
let fileURL = urlPath.appendingPathComponent("index").appendingPathExtension("html")
添加以上行解决了问题。
我实施的实际方法是:
//To copy file in userDocuments
func copyFileFromThisAppMainToUserDocument(fName: String, fExtension:String) -> Bool {
let fileManager = FileManager.default
let urlPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = urlPath.appendingPathComponent(fName).appendingPathExtension(fExtension)
if let bundleURL = Bundle.main.url(forResource: fName, withExtension: fExtension) {
// if file exist, copy it
do {
try fileManager.copyItem(at: bundleURL, to: fileURL)
return true
} catch let error as NSError { // Handle the error
print("\(fName) copy failed! Error:\(error.localizedDescription)")
return false
}
} else {
print("\(fName) not exist in bundle folder")
return false
}
}