Search code examples
javascriptiosiphoneuiwebviewstate-restoration

Restore Position in UIWebView


I need to store the current position in a UIWebView to disk and reload it from disk on a later launch.

What I did before was to store the window.scrollX and window.scrollY with an javascript position. This works good for many cases.

Additionally I store the scale by getting the current:

webView.scrollView.zoomScale

and restore it by setting the viewports initial scale to it with javascript.

All of this works but isn't reliable. Is there an better way?

I read about UIWebView's restorationIdentifier but I'm not sure if I can save it to disk?


Solution

  • In iOS 6 and later, if you assign a value to this view’s restorationIdentifier property, it attempts to preserve its URL history, the scaling and scrolling positions for each page, and information about which page is currently being viewed. During restoration, the view restores these values so that the web content appears just as it did before.

    See more from Apple Programming Guide and a tutorial along with a sample project. You can run it and send the app to the background, then stop running it with Xcode, next time you open the app, it will restore its state to the state before app entering to the background. There can be a small fix on the sample project, in viewDidAppear, if self.restoringState is NO, you call showPage function.