Instance Method


Writes the document data to disk at the sandbox location indicated by a file URL.


func writeContents(_ contents: Any, to url: URL, for saveOperation: UIDocumentSaveOperation, originalContentsURL: URL?) throws



The document data to write to disk. Typically, the data is encapsulated by an NSData object (if a flat file) or an FileWrapper object (if a file package).

If the object encapsulating the document data is of some other type, you should override this method or writeContents(_:andAttributes:safelyTo:for:) to perform the actual writing of the data.


A file URL specifying the location of the document file in the application sandbox.


A constant that indicates whether the document file is being written the first time or whether it is being overwritten. See UIDocumentSaveOperation for details.


A file URL specifying the previous location of the document file (if not nil).


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

Return Value

true if the write operation succeeds, otherwise false.


This method is called by the writeContents(_:andAttributes:safelyTo:for:) to write the actual file data. It is passed the contents object returned from your contents(forType:) implementation. The default implementation of this method supports NSData or FileWrapper contents by asking the contents object to save itself to the corresponding URL.

If you override this method, you may choose to return a different type of data from contents(forType:) or you may choose to not override contents(forType:) and generate the writable data directly within this method. If you override this method, you should not invoke the superclass implementation.

See Also

Writing Document Data

func close(completionHandler: ((Bool) -> Void)? = nil)

Asynchronously closes the document after saving any changes.

func contents(forType: String)

Override this method to return the document data to be saved.

func save(to: URL, for: UIDocumentSaveOperation, completionHandler: ((Bool) -> Void)? = nil)

Saves document data to the specified location in the application sandbox.

func writeContents(Any, andAttributes: [AnyHashable : Any]? = nil, safelyTo: URL, for: UIDocumentSaveOperation)

Ensures that document data is written safely to a specified location in the application sandbox.

var savingFileType: String?

Returns the file type to use for saving a document.

func fileAttributesToWrite(to: URL, for: UIDocumentSaveOperation)

Returns a dictionary of file attributes to associate with the document file when writing or updating it.

func fileNameExtension(forType: String?, saveOperation: UIDocumentSaveOperation)

Returns a file extension to append to the file URL of the document file being written.