【发布时间】:2019-11-29 14:46:49
【问题描述】:
我有一个 iOS/CatalystMacOS 应用程序,可以创建、保存、打开自定义文本文件(带有我自己的文件扩展名)。这工作正常。但是,现在我需要的不仅仅是文字。我也想在这个文件中保存可选文件。显然 macOS(和 iOS?)可以将文件夹视为文件。但我无法让它按要求工作。该文件夹仍被视为文件夹,即使它具有文件扩展名。
这是我用来创建文件夹的代码:
func showNewFilePathDialog(from viewController: UIViewController, saveCompleted: URLCallback?) {
guard !isPresenting else {
return
}
let objectToSave = ...
// Find an available filename
var number = 0
var exportURL: URL!
var data: Data!
var fullFileName = ""
while true {
let numberText = number == 0 ? "" : number.asString()
fullFileName = "baseFileName" + "\(numberText).myFileExtension"
exportURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(fullFileName)
let dict = objectToSave.toDict()
let json = dict.json!
data = json.data(using: .utf8)!
if FileManager.default.fileExists(atPath: exportURL.path) {
number += 1
continue
} else {
break
}
}
do {
try FileManager.default.createDirectory(atPath: exportURL.path, withIntermediateDirectories: true, attributes: nil)
} catch {
NSLog("Couldn't create document directory")
viewController.presentErrorDialog(from: error)
return
}
// 2. Create containing json file
do {
try data.write(to: exportURL.appendingPathComponent("content.json"))
} catch {
viewController.presentErrorDialog(from: error)
return
}
isPresenting = true
self.onSaveDialogComplete = saveCompleted
let pickerViewController = UIDocumentPickerViewController(url: exportURL, in: .exportToService)
pickerViewController.delegate = self
viewController.present(pickerViewController, animated: true)
}
然后它在 macOS finder 中显示如下:
它会在 iOS 中显示类似,也不允许我将文件夹作为单个文件打开。
编辑: 使用 UIDocument/public.composite-content/FileWrapper 似乎也可以,但问题仍然存在:在 macOS finder 中查看时,它仍被视为文件夹。此外,当尝试通过 UIDocumentPickerViewController 从打开对话框打开应用程序时,尝试打开文件包只会打开文件夹,不会让我在应用程序中打开它:(
Edit2: 还尝试删除除 com.apple.package 之外的所有内容,但也不起作用。仍然无法打开我的自定义类型,因为它的行为类似于文件夹。
【问题讨论】:
-
谢谢。但是,仍然无法正常工作。尝试:在文档类型中添加值为 YES 的 LSTypeIsPackage。还尝试将 com.apple.package 添加为“符合 UTI”,并尝试添加版本号
-
Filewrapper 和这个问题有什么关系?
-
谢谢。尝试 FileWrapper/UIDocument 打开/保存文件,但问题仍然相同。 macOS 和 iOS 都将文件视为文件夹,不允许我“作为文件”打开它
标签: ios swift nsfilemanager mac-catalyst uikitformac