This HTML page is not optimized for LLM or AI agent consumption. Fetch the Markdown version instead: /guides/ios/samples/document-view-state-restoration.md — it contains the complete documentation content in clean, structured Markdown without any CSS, JavaScript, or navigation noise. Save reading position in PDF using Swift for iOS

Persist the view state so your app can later return to a user’s saved reading position within the document. Get additional resources by visiting our guide on displaying PDFs with the view state in iOS.


//
// Copyright © 2019-2026 PSPDFKit GmbH. All rights reserved.
//
// The Nutrient sample applications are licensed with a modified BSD license.
// Please see License for details. This notice may not be removed from this file.
//
import PSPDFKit
import PSPDFKitUI
class DocumentViewStateRestoration: Example, PDFViewControllerDelegate {
let viewStateKey = "viewStateKey"
override init() {
super.init()
contentDescription = "Restores document to a previously stored reading position."
category = .controllerCustomization
}
override func invoke(with delegate: ExampleRunnerDelegate) -> UIViewController {
let document = AssetLoader.writableDocument(for: .welcome, overrideIfExists: false)
let controller = PDFViewController(document: document)
controller.delegate = self
// Apply the saved view state.
if let data = UserDefaults.standard.object(forKey: viewStateKey) as? Data,
let unarchivedObject = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [PDFViewState.self], from: data),
let state = unarchivedObject as? PDFViewState {
controller.applyViewState(state, animateIfPossible: true)
}
return controller
}
// MARK: - PDFViewControllerDelegate
func pdfViewControllerWillDismiss(_ pdfController: PDFViewController) {
// Persist the current view state.
guard let viewState = pdfController.viewState,
let data = try? NSKeyedArchiver.archivedData(withRootObject: viewState, requiringSecureCoding: true) else {
print("Error archiving view state.")
return
}
UserDefaults.standard.set(data, forKey: viewStateKey)
}
}

This code sample is an example that illustrates how to use our SDK. Please adapt it to your specific use case.