【发布时间】:2015-11-08 19:20:57
【问题描述】:
感谢您对我上一个问题的帮助。这次想再次求助一个应用,第一次打开时需要下载并缓存内容。
实际上,它是一个 Web 应用程序,其中视图控制器由一个 WebView 组成。为了缓存整个网站(包括“index.htm”、“first.htm”、“second.htm”等),我使用 Kanna 库抓取了整个网站,因此生成了许多链接(生成的 URL)。然后我使用此处回答的方法将每个链接的 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 中显示缓存页面没有问题。
file:///var/mobile/Containers/Data/Application/.../Documents/0.htm file:///var/mobile/Containers/Data/Application/.../Documents/1.htm file:///var/mobile/Containers/Data/Application/.../Documents/2.htm . . .
但是,当前的问题是我丢失了缓存页面之间的链接。例如,在网站中,“index.htm”上有一个链接到“first.htm”的按钮。
现在在加载缓存的“index.htm”(现在是“file:///var/....../0.htm”)后,我将无法先进入缓存的“。 htm”,因为“file:///var/....../1.htm”不在按钮的 HTML 中。
那么我如何检索原始 url 中的缓存文件呢?我应该改变生成文件的方法还是只创建一个包含所有缓存文件路径的新版本网站?
感谢您阅读我的问题。
【问题讨论】:
标签: ios swift caching nsdata nsfilemanager