我正在尝试将文件保存到 icloud 驱动器。我要使用简单版本,不让用户选择保存文件的位置,我只是将其保存在 icloud 驱动器的根目录中。这是我正在使用的代码:
func exportToFiles() {
for page in pages {
let filename = getDocumentsDirectory().appendingPathComponent((page.title ?? "Untitled") + ".png")
if let image = exportImage(page: page, dpi: 300) {
if let data = image.pngData() {
try? data.write(to: filename)
}
}
}
}
func getDocumentsDirectory() -> URL {
let driveURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")
return driveURL!
}
我的里面有这个Info.plist
file:
<key>NSUbiquitousContainers</key>
<dict>
<key>iCloud.com.mysite.myapp</key>
<dict>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerName</key>
<string>myapp</string>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
</dict>
</dict>
在用户界面中,它看起来像是有效的,因为在我点击按钮后有轻微的停顿。但当我查看我的文件时,什么也没有。我究竟做错了什么?
您必须检查并创建“文档”文件夹,并且处理错误也是一个很好的做法:
if let containerUrl = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents") {
if !FileManager.default.fileExists(atPath: containerUrl.path, isDirectory: nil) {
do {
try FileManager.default.createDirectory(at: containerUrl, withIntermediateDirectories: true, attributes: nil)
}
catch {
print(error.localizedDescription)
}
}
let fileUrl = containerUrl.appendingPathComponent("hello.txt")
do {
try "Hello iCloud!".write(to: fileUrl, atomically: true, encoding: .utf8)
}
catch {
print(error.localizedDescription)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)