我想从文档目录中的文件夹显示html文件。我下载的是zip文件,而不是现在解压缩的文件,我想在UIWebView中显示html文件。
我从以下URL下载文件:http://MyURL/D_Word_Meaning_Quiz/data_zip.zip
以这种方式下载文件:-
static func loadFileAsync(url: URL, completion: @escaping (String?, Error?) -> Void) {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)
if FileManager().fileExists(atPath: destinationUrl.path) {
completion(destinationUrl.path, nil)
} else {
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = session.dataTask(with: request, completionHandler:
{
data, response, error in
if error == nil
{
if let response = response as? HTTPURLResponse
{
if response.statusCode == 200
{
if let data = data
{
if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
{
completion(destinationUrl.path, error)
}
else
{
completion(destinationUrl.path, error)
}
}
else
{
completion(destinationUrl.path, error)
}
}
}
}
else
{
completion(destinationUrl.path, error)
}
})
task.resume()
}
}
以这种方式解压缩文件:-
func unzipFolder(filePath: String){
do {
let convertedURL = URL.init(fileURLWithPath: filePath)
print(convertedURL)
let unzipDirectory = try Zip.quickUnzipFile(convertedURL)
print(unzipDirectory)
let htmlUrl = unzipDirectory.appendingPathComponent("index.html")
let req = URLRequest(url: htmlUrl)
DispatchQueue.main.async {
self.webV.loadRequest(req)
}
} catch {
print("Something went wrong")
}
}
打印文档目录:
[file:///private/var/mobile/Containers/Data/Application/1CC5FFEA-DF9A-4590-8628-B9873F775568/Documents/data_zip/, file:///private/var/mobile/Containers/Data/Application/1CC5FFEA-DF9A-4590-8628-B9873F775568/Documents/data_zip.zip]
Receiving this error code in console: NSURLConnection finished with error - code -1100