First of all, I am new to iOS and Swift and come from a background of Android/Java programming. So to me the idea of catching an exception from an attempt to write to a file
a second (recoverable) solution would be to create a very simple ObjectiveC++ function that takes a block and returns an exception.
create a file entitled: ExceptionCatcher.h and add import it in your bridging header (Xcode will prompt to create one for you if you don't have one already)
//
// ExceptionCatcher.h
//
#import
NS_INLINE NSException * _Nullable tryBlock(void(^_Nonnull tryBlock)(void)) {
@try {
tryBlock();
}
@catch (NSException *exception) {
return exception;
}
return nil;
}
Using this helper is quite simple, I have adapted my code from above to use it.
func appendString(string: String, filename: String) -> Bool {
guard let fileHandle = NSFileHandle(forUpdatingAtPath: filename) else { return false }
guard let data = string.dataUsingEncoding(NSUTF8StringEncoding) else { return false }
// will cause seekToEndOfFile to throw an excpetion
fileHandle.closeFile()
let exception = tryBlock {
fileHandle.seekToEndOfFile()
fileHandle.writeData(data)
}
print("exception: \(exception)")
return exception == nil
}