Is there a way to find what exceptions are thrown by Foundation methods in Swift 3? In particular, I'm using the FileManager
class to copy a file from the app bundle to the document directory. The copyItem
method throws an exception if the destination file exists. How to catch that specific exception? The only way I've found is to parse the localizedDescription
, which is ugly and likely not robust:
func copySampleReport() {
let fileManager = FileManager()
let reportName = "MyFile.txt"
if let documentUrl = try? fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false), let reportUrl = Bundle.main.url(forResource: URL(fileURLWithPath: reportName).deletingPathExtension().lastPathComponent, withExtension: URL(fileURLWithPath: reportName).pathExtension) {
debugPrint("Copying \(reportUrl) to \(documentUrl)")
do {
try fileManager.copyItem(at: reportUrl, to: documentUrl.appendingPathComponent(reportName))
debugPrint("File copied succesfully!")
}
catch {
if error.localizedDescription.range(of:"exists") != nil {
debugPrint("File exists at destination")
} else {
debugPrint(error.localizedDescription)
}
}
}
}