有没有办法找到Swift 3中的Foundation方法抛出的异常?特别是,我正在使用FileManager
类将文件从应用程序包复制到文档目录。如果目标文件存在,copyItem
方法将引发异常。如何捕获特定的异常?我发现的唯一方法是解析localizedDescription
,这是丑陋的,可能不健壮:
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)
}
}
}
}