感谢您对我上一个问题的帮助。这次再次请求帮助一个应用程序,第一次打开时需要下载并缓存内容。
事实上,它是一个 Web 应用程序,其中 View Controller 由 WebView 组成。为了缓存整个网站(由“index.htm”、“first.htm”、“second.htm”等组成),我使用 Kanna 库抓取了整个网站,从而生成了许多链接( generatedURL )。然后,我使用此处回答的方法将每个链接的 HTML 写入单个文件。Read and write data from text file
这是我在 AppDelegate.swift 的 didFinishLaunchingWithOptions 中的代码。
// get the documents folder url
let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
for index in 0..<generatedURL.count {
let fileDestinationUrl = documentDirectoryURL.URLByAppendingPathComponent(String(index)+".htm")
cachedURL[index] = fileDestinationUrl //store the cached urls
let fileURL = NSURL(string: generatedURL[index])
//if (NSFileManager.defaultManager().fileExistsAtPath(fileDestinationUrl)) {
let data = NSData(contentsOfURL: fileURL!)
if (data != nil) {
//writing to disk
data?.writeToURL(fileDestinationUrl, atomically: true)
// saving was successful. any code posterior code goes here
//reading from disk
do {
let mytext = try String(contentsOfURL: fileDestinationUrl, encoding: NSUTF8StringEncoding)
print(fileDestinationUrl)
print(mytext) // "some text\n"
} catch let error as NSError {
print("error loading from url \(fileDestinationUrl)")
print(error.localizedDescription)
}
}
// } else {
// print("The files already exist")
// //reading from disk
// do {
// let mytext = try String(contentsOfURL: fileDestinationUrl, encoding: NSUTF8StringEncoding)
// //print(fileDestinationUrl)
// //print(mytext) // "some text\n"
// } catch let error as NSError {
// print("error loading from url \(fileDestinationUrl)")
// print(error.localizedDescription)
// }
//
// }
}
运行程序时,所有链接的 HTML 都本地存储在这些文件中。加载 HTML 并在 WebView 中显示缓存页面没有问题。
文件:///var/mobile/Containers/Data/Application/.../Documents/0.htm 文件:///var/mobile/Containers/Data/Application/.../Documents/1.htm 文件:///var/mobile/Containers/Data/Application/.../Documents/2.htm . . .
但是,当前的问题是我丢失了缓存页面之间的链接。例如,在网站中,“index.htm”上有一个链接到“first.htm”的按钮。
现在加载缓存的“index.htm”(现在是“file:///var/....../0.htm”)后,我将无法转到缓存的“first.htm”。 htm”,因为“file:///var/....../1.htm”不在按钮的 HTML 中。
那么如何在原始 URL 中检索缓存文件呢?我应该更改生成文件的方法还是仅使用所有缓存的文件路径创建网站的新版本?
感谢阅读我的问题。
最佳答案
好的,我想我现在可以回答我自己的问题了。在包含 webView 对象的 ViewController.swift 中使用以下函数,如果单击原始 url,我可以提示 webView 加载缓存的 url。
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.LinkClicked {
if (request.URL!.absoluteString == generatedURL[index] {
let requestObj = NSMutableURLRequest(URL: appDelegate.cachedURL[index]!);
webView.loadRequest(requestObj)
//return false
}
}
return true
}
关于ios - 如何在 iOS swift 中检索缓存文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597988/