Do you have issues in writing to and reading from files in iOS? Is it failing with NSPosixErrorDomain error codes? We will start with diagnosis of common cases and move to advanced cases
- As always check if you have valid NSData to write
- Check if you have a valid URL path
- Check if your subdirectories exist
If nothing works above you need to use a file writing API which can throw error, like the one below
public func writeToFile(path: String, options writeOptionsMask: NSDataWritingOptions) throws
instead of something like this
public func writeToFile(path: String, atomically useAuxiliaryFile: Bool) -> Bool
to catch an error. 95% of the error cases falls within the above said.
There is one more case that is rarely discussed. Hard to diagnose too – the case of handling Absolute and Relative URLs. Lets discuss that below.
Lets assume if you have a function to write image to a path as shown below. At the end of file write we capture both full file path and relative file path to read later.

Here we retrieve the image from full file path. This one will work but only for the current active session. The image path will look like this
If your print the path it will look something like this
/var/mobile/Containers/Data/Application/A3955D86-3C02-48F9-AB5C-3582D8383F6E/Documents/Folder/image.png

If you try to access the file within the same session, it would still work. But if you try to access the image in a different session you would get a “File not found” error.
The path of image in previous session, had you stored it would be
/var/mobile/Containers/Data/Application/A3955D86-3C02-48F9-AB5C-3582D8383F6E/Documents/Folder/image.png
In a newer session the image would be moved by iOS to
/var/mobile/Containers/Data/Application/937FEDCD-1B90-4F38-9C3D-F86627BE3D3C/Documents/Folder/image.png
Note the change in folder path. Its evident that folder signature is generated dynamically by iOS. I believe its an excellent mechanism to safeguard data.
So back to our issue. Look at the next case. We retrieve relative file path and we construct absolute path by appending with documents directory.

Relative path will be of the following format
/Folder/image.png
when you append with Documents directory first time, the path of image would be
/var/mobile/Containers/Data/Application/A3955D86-3C02-48F9-AB5C-3582D8383F6E/Documents/Folder/image.png
And when you reconstruct the image path in a different session it would be
/var/mobile/Containers/Data/Application/937FEDCD-1B90-4F38-9C3D-F86627BE3D3C/Documents/Folder/image.png
You can validate by accessing the file path to confirm file existence.
Moral of the story : Use relative file URLs to handle files. Always construct absolute paths dynamically