NSError objects that secure Objective-C methods return

Some of the ACFileHandle secure methods and some of the category methods take a pointer to an NSError object as a parameter. These methods can set the domain and code properties on the NSError object to:

the domain NSPOSIXErrorDomain, with the code property set to errno values.

other domains, such as NSCocoaErrorDomain. The possible values of the code property are the same as regular Objective-C methods.

the domain ACErrorDomain, defined in ACError.h. The possible values of the code property are defined in the enumeration in ACError.h. These values are the same values returned by the ACSecureFileLastError() method.

Of particular interest when working with secure file I/O APIs are the errors ACE_NO_KEYS_ERROR and ACE_BAD_KEY_OR_CORRUPT_DATA_ERROR. These errors indicate an encryption failure.

For more information, see NSError objects that secure Objective-C methods return.

Objective-C example

The following example shows how to check the NSError object returned in a secure write method:

- (void)errorHandlingExample
{
    // Create data to be securely stored.
    NSData *data = [@"secret data" dataUsingEncoding:NSASCIIStringEncoding];
 
    // Set up a couple of data writing options.
    NSDataWritingOptions options = NSDataWritingAtomic | NSDataWritingFileProtectionComplete;
 
    NSString *secureFilename = @"/tmp/data.sec";
    NSError *error;
 
	if (! [data writeToSecureFile:secureFilename options:options error:&error]) {
 
		if ([[error domain] isEqualToString:ACErrorDomain] &&
                                             [error code] == ACE_NO_KEYS_ERROR) {
 
		   // Provide logic to handle the situation when 
                  // the encryption key is not available.
		}
	}
} 

Swift example

The following example shows how to check the NSError object returned in a secure write method:

func errorHandlingExample() {
 
	// Create data to be securely stored.
	let data = "secret data".data(using: .ascii)! as NSData
 
	// Set up a couple of data writing options.
	let options: NSData.WritingOptions = [.atomic, .completeFileProtection]
 
	let secureFilename = "/tmp/data.sec"
 
	do {
		try data.write(toSecureFile: secureFilename, options: options)
	}
 
	catch(let error as NSError) {
 
		if (error.domain == ACErrorDomain && error.code == ACErrorNoKeys) {
 
		     	// Provide logic to handle the situation when
			// the encryption key is not available.
		}
	}
}