在iOS的应用程序中,需要使用文件系统时,必须获取相应的授权。在使用文档目录保存文件时,必须检查并获取相应的许可。以下是检查并获取许可的代码示例:
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("example.txt")
do {
try "Hello, World!".write(to: fileURL, atomically: true, encoding: .utf8)
print("File saved!")
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
在此示例中,我们首先获取文档目录的 URL,然后将文件名称附加到该 URL 上以创建完整的文件 URL。我们还使用 write(to:atomically:encoding:)
方法将字符串写入文件。
如果你尝试写入文件,并且遇到 Permission error
(权限错误)错误,则可以添加以下代码以获取许可:
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("example.txt")
if fileManager.fileExists(atPath: fileURL.path) {
print("File already exists!")
} else {
do {
try "".write(to: fileURL, atomically: true, encoding: .utf8)
print("Permission granted!")
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
}
在此示例中,我们使用 fileExists(atPath:)
方法检查文件是否存在。如果文件不存在,则通过 write(to:atomically:encoding:)
方法写入一个空字符串。如果使用 try
块时出现错误,则会抛出错误并捕获它。否则,我们输出 “Permission granted”(权限已授权)消息。
通过这种方法,你可以避免“Permission error when saving to documentDirectory”错误,并在 iOS 应用程序中处理文件系统和目录。