简体   繁体   中英

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. 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

Here is my code in the didFinishLaunchingWithOptions of AppDelegate.swift.

            // 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. There's no problems in loading the HTML and thereby displaying the cached page in the 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 . . .

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".

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.

So how do I retrieve the cached files in their original urls? 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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