iOS Developer Library

Developer

UIKit Framework Reference UIDocument Class Reference

Options
Deployment Target:

On This Page
Language:

UIDocument

The UIDocument class is an abstract base class for managing the data of documents. More...

Inheritance


Conforms To


Import Statement


import UIKit @import UIKit;

Availability


Available in iOS 5.0 and later.
  • Returns a document object initialized with its file-system location.

    Declaration

    Swift

    init(fileURL url: NSURL)

    Objective-C

    - (instancetype)initWithFileURL:(NSURL *)url

    Parameters

    url

    A file URL identifying the location in the application sandbox where document data is to be written. Passing in nil or an empty URL results in the throwing of an NSInvalidArgumentException.

    Return Value

    A UIDocument object or nil if the object could not be created.

    Discussion

    After you create a document object and no file exists for it yet, you should next call the saveToURL:forSaveOperation:completionHandler: to write the document to its file-system location in the application sandbox. If url locates an existing document file, call openWithCompletionHandler: after creating the document object. The second parameter of this method, the save operation constant, should be UIDocumentSaveForCreating when there is no document file yet. In the completion handler, if you want the document to be automatically synced with other devices and computers on which the application is installed, you should call the NSFileManager method setMobileSynchEnabled:forItemAtURL:destinationDirectory:replacementURL:error:.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

    See Also

    fileURL

  • Opens a document asynchronously.

    Declaration

    Swift

    func openWithCompletionHandler(_ completionHandler: ((Bool) -> Void)?)

    Objective-C

    - (void)openWithCompletionHandler:(void (^)(BOOL success))completionHandler

    Parameters

    completionHandler

    A block with code to execute after the open operation concludes. The block returns no value and has one parameter:

    success

    YEStrue if the open operation succeeds, otherwise NOfalse.

    The block is invoked on the main queue.

    Discussion

    Call this method to begin the sequence of method calls that opens and reads a document asynchronously. The method obtains the file-system location of the document from the fileURL property. After the open operation concludes, the code in completionHandler is executed.

    You can override this method if you want custom document-opening behavior, but if you do it is recommended that you call the superclass implementation first (super). If you don’t call super, you should use the NSFileCoordinator class to implement coordinated reading. The default implementation sets up file coordination and then calls performAsynchronousFileAccessUsingBlock: to schedule the document-reading work for execution on a background queue. The queued task then calls readFromURL:error:.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Override this method to load the document data into the app’s data model.

    Declaration

    Swift

    func loadFromContents(_ contents: AnyObject, ofType typeName: String, error outError: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError

    Parameters

    contents

    An object encapsulating the document data to load. This object is either an instance of the NSData class (for flat files) or the NSFileWrapper class (for file packages).

    typeName

    The file type of the document, a Uniform Type Identifier (UTI) based on the file extension of fileURL. You can obtain the default value of the file type from the fileType property.

    outError

    If you cannot load the document data for any reason, return by indirection an NSError object that encapsulates the reasons you can’t. Otherwise, ignore this parameter.

    Return Value

    YEStrue if you successfully load the document, NOfalse otherwise.

    Discussion

    Override this method to accept and load the data for a document. After UIDocument reads the document data from the file located at fileURL it calls your subclass, passing the data to the subclass in this method. This method is called on the queue that the openWithCompletionHandler: method was called on (typically, the main queue).

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Reads the document data in a file at a specified location in the application sandbox.

    Declaration

    Swift

    func readFromURL(_ url: NSURL, error outError: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)readFromURL:(NSURL *)url error:(NSError **)outError

    Parameters

    url

    A file URL that identifies the location of the document file in the application sandbox. This file URL is typically the one returned by the fileURL property.

    outError

    If the document file cannot be read, returns by indirection an error object that encapsulates the reasons why the read operation failed.

    Return Value

    YEStrue if the read operation succeeds, otherwise NOfalse.

    Discussion

    Typical UIDocument subclasses should not need to call this method directly, especially if the entire file is read at once. The default implementation calls loadFromContents:ofType:error: on the queue on which openWithCompletionHandler: was called to provide the UIDocument subclass with the document data object.

    Subclasses that want more control over the reading of the document file—for example, that want to read a large document file incrementally—can override this method. It is not necessary for these subclasses to call the superclass implementation (super).

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Schedules a document-reading or document-writing operation on a concurrent background queue.

    Declaration

    Swift

    func performAsynchronousFileAccessUsingBlock(_ block: (() -> Void)!)

    Objective-C

    - (void)performAsynchronousFileAccessUsingBlock:(void (^)(void))block

    Parameters

    block

    A block that is invoked as the task to execute on the background queue. The block returns no value and takes no parameters.

    Discussion

    A typical UIDocument subclasses—that is, one that overrides contentsForType:error: and loadFromContents:ofType:error:— does not need to call this method.

    The default implementations of saveToURL:forSaveOperation:completionHandler: and openWithCompletionHandler: call this method to serialize file access. If you override these methods and do not call super, you should call this method to serialize file access on a background queue. If you directly call the readFromURL:error: method, you should wrap that call in the block passed into performAsynchronousFileAccessUsingBlock:.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Reverts a document to the most recent document data stored on-disk.

    Declaration

    Swift

    func revertToContentsOfURL(_ url: NSURL, completionHandler completionHandler: ((Bool) -> Void)?)

    Objective-C

    - (void)revertToContentsOfURL:(NSURL *)url completionHandler:(void (^)(BOOL success))completionHandler

    Parameters

    url

    A file URL locating the most recent version of the document file in the application’s sandbox.

    completionHandler

    A block with code to execute after the reversion operation concludes. The block returns no value and has one parameter:

    success

    YEStrue if the reversion operation succeeds, otherwise NOfalse.

    The block is invoked on the main queue.

    Discussion

    You call this method to discard all unsaved document modifications and replace the document's contents by reading the file or file package located by url. The default implementation brackets the reversion operation between disableEditing and enableEditingbecause the document should not accept user changes during this period. Subclasses that override this method must call the superclass implementation (super) or use the NSFileCoordinator class to initiate a coordinated read.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Overridden to disable editing when it is unsafe to make changes to a document.

    Declaration

    Swift

    func disableEditing()

    Objective-C

    - (void)disableEditing

    Discussion

    Subclasses should override this method to prevent the user from editing the document when it is unsafe to do so, such as during a save-and-close or revert operation. When editing is safe again, UIKit class calls enableEditing. The default implementation of this method does nothing.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Overridden to enable editing when it is safe again to make changes to a document.

    Declaration

    Swift

    func enableEditing()

    Objective-C

    - (void)enableEditing

    Discussion

    Subclasses should override this method to allow the user to edit the document when it is safe to do so. This method override should be paired with an override of disableEditing. The default implementation of this method does nothing.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Returns whether the document has any unsaved changes.

    Declaration

    Swift

    func hasUnsavedChanges() -> Bool

    Objective-C

    - (BOOL)hasUnsavedChanges

    Return Value

    YEStrue if the document has unsaved changes, otherwise NOfalse.

    Discussion

    The default implementation of autosaveWithCompletionHandler: initiates a save if this method returns YEStrue. Typical subclasses do not need to override the hasUnsavedChanges method. To implement change tracking, they should instead use an NSUndoManager object (assigned to undoManager) to register changes or call updateChangeCount: every time the user makes a change; UIKit then automatically determines whether there are unsaved changes.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Update the change counter by indicating the kind of change.

    Declaration

    Swift

    func updateChangeCount(_ change: UIDocumentChangeKind)

    Objective-C

    - (void)updateChangeCount:(UIDocumentChangeKind)change

    Parameters

    change

    A constant that indicates whether a change has been made, cleared, undone, or redone. See Document Save Kind for more information.

    Discussion

    Calling this method can affect the value returned by hasUnsavedChanges. You should not need to call method this if you access an NSUndoManager object from the undoManager property (or assign a custom one to it) and register changes with the undo manager.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • The undo manager for the document.

    Declaration

    Swift

    var undoManager: NSUndoManager

    Objective-C

    @property(retain) NSUndoManager *undoManager

    Discussion

    This property holds the document's undo manager (an NSUndoManager object) or nil if this property has not been accessed or set. Accessing this property creates a default undo manager if a custom undo manager has not been set.

    The undo manager for the document is registered as an observer of various NSUndoManager notifications so that it can call updateChangeCount: as the user makes undoable changes to the document. When a subclass sets this property and implements registers changes with it, it does not need to call updateChangeCount: directly or (more rarely) override hasUnsavedChanges.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Overridden to return a change token for a specific save operation.

    Declaration

    Swift

    func changeCountTokenForSaveOperation(_ saveOperation: UIDocumentSaveOperation) -> AnyObject

    Objective-C

    - (id)changeCountTokenForSaveOperation:(UIDocumentSaveOperation)saveOperation

    Parameters

    saveOperation

    A constant that indicates whether the save operation is writing a new file or overwriting an existing one. See Document Save Operation for descriptions of these constants.

    Return Value

    An object to use as a change-count token.

    Discussion

    To get autosaving capabilities for your documents, you must implement change tracking. Typically you do this by using an NSUndoManager object (assigned to undoManager property) to register changes or by calling the updateChangeCount: method every time the user makes a change; UIKit then automatically determines whether there are unsaved changes and returns the proper value from hasUnsavedChanges. If you take neither of these approaches (and you want the autosaving feature), you must implement this method as well as updateChangeCountWithToken:forSaveOperation: and hasUnsavedChanges.

    You implement this particular method to return a change-count token that UIKit uses to encapsulate the history of document changes for a particular save operation. The token can be any object that represents the current change state of the document. This method is called at the start of the default implementation of the saveToURL:forSaveOperation:completionHandler: method. At the end of this default implementation, it calls the updateChangeCountWithToken:forSaveOperation: method, passing in the change-count token. You implement the latter method to compare the token with the one returned earlier; by doing so, you can determine if the document has acquired new unsaved changes between the start and end of an asynchronous write operation. You can then return the proper value from your override of hasUnsavedChanges.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Overridden to update the change count with reference to a change-count token passed in by UIKit.

    Declaration

    Swift

    func updateChangeCountWithToken(_ changeCountToken: AnyObject, forSaveOperation saveOperation: UIDocumentSaveOperation)

    Objective-C

    - (void)updateChangeCountWithToken:(id)changeCountToken forSaveOperation:(UIDocumentSaveOperation)saveOperation

    Parameters

    changeCountToken

    An object to use as a change-count token. UIDocument obtained this token earlier by calling changeCountTokenForSaveOperation:.

    saveOperation

    A constant that indicates whether the save operation is writing a new file or overwriting an existing one. See Document Save Operation for descriptions of these constants.

    Discussion

    To get autosaving capabilities for your documents, you must implement change tracking. Typically you do this by using an NSUndoManager object (assigned to undoManager property) to register changes or by calling the updateChangeCount: method every time the user makes a change; UIKit then automatically determines whether there are unsaved changes and returns the proper value from hasUnsavedChanges. If you take neither of these approaches (and you want the autosaving feature), you must implement this method as well as changeCountTokenForSaveOperation: and hasUnsavedChanges.

    You implement the changeCountTokenForSaveOperation: method to return a change-count token that UIKit uses to encapsulate the history of document changes for a particular save operation. The token can be any object that represents the current change state of the document. This method is called at the start of the default implementation of the saveToURL:forSaveOperation:completionHandler: method. At the end of this default implementation, UIDocument calls this method (updateChangeCountWithToken:forSaveOperation:), passing in the change-count token. You implement this method to compare the token with the one returned earlier; by doing so, you can determine if the document has acquired new unsaved changes between the start and end of an asynchronous write operation. You can then return the proper value from your override of hasUnsavedChanges.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Called by UIKit to initiate automatic saving of documents with unsaved changes.

    Declaration

    Swift

    func autosaveWithCompletionHandler(_ completionHandler: ((Bool) -> Void)?)

    Objective-C

    - (void)autosaveWithCompletionHandler:(void (^)(BOOL success))completionHandler

    Parameters

    completionHandler

    A block with code to execute after automatic saving concludes. The block returns no value and has one parameter:

    success

    YEStrue if the autosaving operation succeeds, otherwise NOfalse.

    The block is invoked on the calling queue.

    Discussion

    UIDocument periodically invokes this method to initiate a save operation if there are unsaved changes. You should not call this method directly. Subclasses can override it if they want to do special things with autosaving. The default implementation of this method invokes the hasUnsavedChanges method and, if that returns YEStrue, it invokes the saveToURL:forSaveOperation:completionHandler: method.

    This method should only be invoked for period-based saves. You may invoke it with the success parameter of the completion-handler parameter set to NOfalse and return; this makes it safe to not actually save when autosaveWithCompletionHandler: is invoked. However, if you call saveToURL:forSaveOperation:completionHandler:, saving of document data must occur.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • An object encapsulating a user activity supported by this document.

    Declaration

    Swift

    var userActivity: NSUserActivity?

    Objective-C

    @property(nonatomic, retain) NSUserActivity *userActivity

    Discussion

    NSDocument automatically creates NSUserActivity objects for iCloud-based documents if the app’s Info.plist property list file includes a CFBundleDocumentTypes key of NSUbiquitousDocumentUserActivityType. The value of NSUbiquitousDocumentUserActivityType is a string that is used for the NSUserActivity object’s activity type. The document's URL is put into the NSUserActivity object’s userInfo dictionary with the NSUserActivityDocumentURLKey.

    On iOS, for NSUserActivity objects managed by UIKit to become current, you must either call becomeCurrent explicitly or have the document’s NSUserActivity object also set on a UIViewController object that is in the view hierarchy when the app comes to the foreground.

    If the document becomes non-ubiquitous, its userActivity property is nil. Any NSUserActivity objects that are managed by AppKit but which have no associated documents (or responders) are automatically invalidated.

    This property can be used from any thread. It is KVO observable in case the userActivity object is being shared with other objects that need to be kept in sync as the document moves into and out of iCloud.

    Import Statement

    import UIKit

    Availability

    Available in iOS 8.0 and later.

  • Restores the state needed to continue the given user activity.

    Declaration

    Swift

    func restoreUserActivityState(_ activity: NSUserActivity)

    Objective-C

    - (void)restoreUserActivityState:(NSUserActivity *)activity

    Parameters

    activity

    The user activity to be continued.

    Discussion

    Subclasses override this method to restore the responder’s state with the given user activity. The override should use the state data contained in the userInfo dictionary of the given user activity to restore the object.

    User activities managed by NSDocument can be restored automatically, if NOfalse is returned from application:continueActivity:restorationHandler: or if it is unimplemented. In this situation, the document is opened by the NSDocumentController method openDocumentWithContentsOfURL:display:completionHandler: and receives a restoreUserActivityState: message.

    Import Statement

    import UIKit

    Availability

    Available in iOS 8.0 and later.

  • Updates the state of the given user activity.

    Declaration

    Swift

    func updateUserActivityState(_ activity: NSUserActivity)

    Objective-C

    - (void)updateUserActivityState:(NSUserActivity *)activity

    Parameters

    activity

    The user activity to be updated.

    Discussion

    The default implementation of this method puts the document’s fileURL into the NSUserActivity object’s userInfo dictionary with the NSUserActivityDocumentURLKey. UIDocument automatically sets the needsSave property of the NSUserActivity object to YEStrue when the fileURL changes.

    Import Statement

    import UIKit

    Availability

    Available in iOS 8.0 and later.

  • Called or overridden to handle an error that occurs during an attempt to read, save, or revert a document.

    Declaration

    Swift

    func handleError(_ error: NSError, userInteractionPermitted userInteractionPermitted: Bool)

    Objective-C

    - (void)handleError:(NSError *)error userInteractionPermitted:(BOOL)userInteractionPermitted

    Parameters

    error

    An object encapsulating information about an error encountered in an attempt to open, save, or revert a document. The error domain is NSCocoaErrorDomain. The error code is one of the enum constants declared in FoundationErrors.h.

    userInteractionPermitted

    If NOfalse, no attempt is (or should be) made to present a modal view to the user. This value can be NOfalse in cases such as when a save operation fails while the application is being suspended. If this parameter is YEStrue, UIKit or your override may present error information to the user in a modal view and (optionally) allow the user to resolve the error.

    Discussion

    Typical UIDocument subclasses do not need to call or override this method. Instead, they can observe the UIDocumentStateChangedNotification notification to be notified of changes in document state. In their notification handler, they can check the value of the documentState property and proceed accordingly. See Conflict Resolution and Error Handling for a discussion of this.

    If you are using managed documents (instances of the UIManagedDocument subclass), you must subclass this method and, if desired, the finishedHandlingError:recovered: method. Subclassing allows your app to observe errors in saving or validation. The UIDocumentStateChangedNotification notification does not contain a userInfo dictionary and so does not convey specific error information.

    If you directly call any of the advanced reading and writing methods that have an error-object parameter (for example, writeContents:andAttributes:safelyToURL:forSaveOperation:error:) and that call returns an NSError object by indirection, you should call this method (handleError:userInteractionPermitted:), passing in the error object.

    This method is called by the default implementations of openWithCompletionHandler: and saveToURL:forSaveOperation:completionHandler: when UIDocument encounters a reading or writing error, respectively.

    If you override this method and do not invoke the superclass implementation (super), you are responsible for the following:

    • Calling finishedHandlingError:recovered: when you are finished handling the error—for example, when the application does not require any additional user feedback about the error.

    • Implementing userInteractionNoLongerPermittedForError: to conclude error handling immediately. If userInteractionPermitted is NOfalse, you should immediately handle the error and call finishedHandlingError:recovered: within the context of the handleError:userInteractionPermitted:

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Tells UIKit that you have finished handled the error.

    Declaration

    Swift

    func finishedHandlingError(_ error: NSError, recovered recovered: Bool)

    Objective-C

    - (void)finishedHandlingError:(NSError *)error recovered:(BOOL)recovered

    Parameters

    error

    An error object encapsulating information about the error.

    recovered

    YEStrue if you recovered from the error, otherwise NOfalse.

    Discussion

    This method is called by default when handling of an error (including any user interaction) is complete. Subclasses need to call this method only if they override handleError:userInteractionPermitted: and do not call the superclass implementation (super). If you override this method, you must call super.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Sent when it is no longer safe to proceed without immediately handling the error.

    Declaration

    Swift

    func userInteractionNoLongerPermittedForError(_ error: NSError)

    Objective-C

    - (void)userInteractionNoLongerPermittedForError:(NSError *)error

    Parameters

    error

    An error object encapsulating information about the error.

    Discussion

    UIKit calls this method when it is no longer safe to proceed without immediately handling the error, such as when the application is being suspended. Subclasses that override this method must immediately end error handling (including dismissing any interactive user interface) and call finishedHandlingError:recovered: before returning. It is only necessary to override this method if you override handleError:userInteractionPermitted: without invoking the superclass implementation (super).

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Constants for specifying the kind of change to a document.

    Declaration

    Swift

    enum UIDocumentChangeKind : Int { case Done case Undone case Redone case Cleared }

    Objective-C

    enum { UIDocumentChangeDone, UIDocumentChangeUndone, UIDocumentChangeRedone, UIDocumentChangeCleared }; typedef NSInteger UIDocumentChangeKind;

    Constants

    • Done

      UIDocumentChangeDone

      A change has been made to the document.

      Available in iOS 5.0 and later.

    • Undone

      UIDocumentChangeUndone

      A change to the document has been undone.

      Available in iOS 5.0 and later.

    • Redone

      UIDocumentChangeRedone

      An undone change to the document has been redone.

      Available in iOS 5.0 and later.

    • Cleared

      UIDocumentChangeCleared

      The document is cleared of outstanding changes.

      Available in iOS 5.0 and later.

    Discussion

    You specify one of these constants as a parameter of the updateChangeCount: method.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • Constants for specifying the type of save operation.

    Declaration

    Swift

    enum UIDocumentSaveOperation : Int { case ForCreating case ForOverwriting }

    Objective-C

    enum { UIDocumentSaveForCreating, UIDocumentSaveForOverwriting }; typedef NSInteger UIDocumentSaveOperation;

    Constants

    • ForCreating

      UIDocumentSaveForCreating

      The document is being saved for the first time.

      Available in iOS 5.0 and later.

    • ForOverwriting

      UIDocumentSaveForOverwriting

      The document is being saved by overwriting the current version.

      Available in iOS 5.0 and later.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.

  • The document state.

    Declaration

    Swift

    struct UIDocumentState : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var Normal: UIDocumentState { get } static var Closed: UIDocumentState { get } static var InConflict: UIDocumentState { get } static var SavingError: UIDocumentState { get } static var EditingDisabled: UIDocumentState { get } }

    Objective-C

    enum { UIDocumentStateNormal = 0, UIDocumentStateClosed = 1 << 0, UIDocumentStateInConflict = 1 << 1, UIDocumentStateSavingError = 1 << 2, UIDocumentStateEditingDisabled = 1 << 3 }; typedef NSInteger UIDocumentState;

    Constants

    • Normal

      UIDocumentStateNormal

      The document is open, editing is enabled, and there are no conflicts or errors associated with it.

      Available in iOS 5.0 and later.

    • Closed

      UIDocumentStateClosed

      There was an error in reading the document: the document has either not been successfully opened, or has been since closed. The document properties might not be valid.

      Available in iOS 5.0 and later.

    • InConflict

      UIDocumentStateInConflict

      Conflicts exist for the document file located at fileURL. You can access these conflicting document versions by calling the otherVersionsOfItemAtURL: class method of the NSFileVersion class. This method returns an array of NSFileVersion objects. You can then resolve the conflicting versions—for example, programmatically attempt to merge the versions or present the document versions to the user and request him or her to pick one.

      Available in iOS 5.0 and later.

    • SavingError

      UIDocumentStateSavingError

      There was an error in saving or reverting the document.

      Available in iOS 5.0 and later.

    • EditingDisabled

      UIDocumentStateEditingDisabled

      The document is busy and it is not currently safe for user edits. This state is set just before UIDocument calls the disableEditing method. It calls enableEditing when it becomes safe to edit again. UIDocument also sets this state when an error prevents the reverting of a document.

      Available in iOS 5.0 and later.

    Discussion

    A UIDocument object stores the current state of the document in the documentState property. To receive notifications about changes in document state, observe the UIDocumentStateChangedNotification notification.

    Import Statement

    import UIKit

    Availability

    Available in iOS 5.0 and later.