ios - 如何在 iOS swift 中检索缓存文件?

标签 ios swift caching nsdata nsfilemanager

感谢您对我上一个问题的帮助。这次再次请求帮助一个应用程序,第一次打开时需要下载并缓存内容。

事实上,它是一个 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/

相关文章:

ios - iOS什么时候分配内存和释放内存? (相对于导航和选项卡 Controller 的默认行为)

ios - 从 iPhone 4s 到 iPhone 6+ 具有自适应布局的间距布局元素

android - 高效地缓存、传递和查看位图 Android

ios - 在 ScrollView iOS sdk 中缩放图像

ios - 如何在另一个 UIViewController 中编辑 UICollectionView 项?

iphone - 如何将 uibutton 添加到自定义注释 View

ios - 检索 UserDefaults 后刷新 viewdidload 上的 collectionView

ios - 应用程序不断崩溃发现 Nil Swift

java - 如何使用 Powermockito 测试缓存

ios - NSURLCache 的 removeCachedResponseForRequest 没有效果