Instance Method


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


func writeContents(_ contents: Any, andAttributes additionalFileAttributes: [AnyHashable : Any]? = nil, safelyTo url: URL, for saveOperation: UIDocumentSaveOperation) 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(_:to:for:originalContentsURL:) to perform the actual writing of the data.


A dictionary of FileManager file attributes to assign to the document file. The default implementation obtains these file attributes by calling fileAttributesToWrite(to:for:).


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


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 save(to:for:completionHandler:) method to save the file data (and associated attributes in the case of an FileWrapper). It creates temporary files and directories as necessary so that successful saves can be completed atomically and failed saves can be rolled back cleanly. This method calls writeContents(_:to:for:originalContentsURL:) to save the contents object, passing the location for the new saved file in the toURL parameter and the location of the previously existing file in the originalContentsURL parameter, if this is an overwrite operation.

If you want to change how file data is saved, you generally override the writeContents(_:to:for:originalContentsURL:) method instead of this method. Additionally, you don’t need to call this method directly unless you are overriding the save(to:for:completionHandler:) method.

See Also

Related Symbols

func contents(forType: String)

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

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

Asynchronously closes the document after saving any changes.

func writeContents(Any, to: URL, for: UIDocumentSaveOperation, originalContentsURL: URL?)

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