简体   繁体   English

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

[英]How do I retrieve cached files in iOS swift?

Thanks for the help in my last question. 感谢您对我的上一个问题的帮助。 This time I would like to ask for help again for an application whose contents need to be downloaded and cached when it's opened for the first time. 这次,我想再次寻求一个应用程序的帮助,该应用程序的内容在首次打开时需要下载并缓存。

Indeed it's a web app where the view controller consists of a WebView. 实际上,这是一个Web应用程序,其中视图控制器由WebView组成。 In order to cache the whole website (which consists of "index.htm", "first.htm, "second.htm" and etc), I have scraped the whole site using the Kanna library and hence generated numerous links (generatedURL). Then I write the HTML of each link into a single file using the approach answered here. Read and write data from text file 为了缓存整个网站(由“ index.htm”,“ first.htm,“ second.htm”等组成),我使用Kanna库抓取了整个网站,并因此生成了许多链接(generatedURL)。然后,我使用此处回答的方法将每个链接的HTML写入单个文件, 并从文本文件中读取和写入数据

Here is my code in the didFinishLaunchingWithOptions of AppDelegate.swift. 这是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)
//                }
//                
//            }

        }

When running the program, the HTMLs of all the links are stored locally in those files. 运行该程序时,所有链接的HTML都本地存储在这些文件中。 There's no problems in loading the HTML and thereby displaying the cached page in the WebView. 加载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 . 文件:///var/mobile/Containers/Data/Application/.../Documents/0.htm文件:///var/mobile/Containers/Data/Application/.../Documents/1.htm文件: ///var/mobile/Containers/Data/Application/.../Documents/2.htm。 . .

However, the current problem is that I lost the linkage between the cached pages. 但是,当前的问题是我丢失了缓存页面之间的链接。 For example, in the website, there is a button on "index.htm" that links to "first.htm". 例如,在网站上,“ index.htm”上有一个链接到“ first.htm”的按钮。

Now after loading the cached "index.htm" which is now "file:///var/....../0.htm", I won't be able to go to the cached "first.htm" because "file:///var/....../1.htm" is not in the HTML of the button. 现在,在加载缓存的“ index.htm”(现在为“ file:///var/....../0.htm”)之后,我将无法转到缓存的“ first.htm”,因为按钮的HTML中没有“ file:///var/....../1.htm”。

So how do I retrieve the cached files in their original urls? 那么,如何在原始URL中检索缓存的文件? Should I change the approach of generating the file or just create a new version of the website with all the cached file paths? 我应该更改生成文件的方法还是仅创建具有所有缓存文件路径的网站的新版本?

Thanks for reading my question. 感谢您阅读我的问题。

OK, i think I can answer my own question now. 好的,我想我现在可以回答自己的问题。 Using the following function in the ViewController.swift containing the webView object, I can prompt the webView to load the cached url if the original url is clicked. 使用包含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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM