使用FileManager保存/创建将其视为文件的文件夹

我有一个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中看起来像这样:

使用FileManager保存/创建将其视为文件的文件夹

它将在iOS中显示类似,也不允许我将文件夹作为一个文件打开。

编辑:似乎也可以使用UIDocument / public.composite-content / FileWrapper,但问题仍然存在:在macOS Finder中查看时,仍被视为文件夹。另外,当尝试通过UIDocumentPickerViewController从打开对话框打开应用程序时,尝试打开文件捆绑包只会打开文件夹,而不会让我将其打开到应用程序中:(

这是我的info.list导出类型UTI:

使用FileManager保存/创建将其视为文件的文件夹

Edit2 :还尝试删除了com.apple.package以外的所有内容,但均不起作用。仍然无法打开我的自定义类型,因为它的行为就像一个文件夹。

www_melody 回答:使用FileManager保存/创建将其视为文件的文件夹

使其正常工作。似乎我的应用程序的旧版本正在干扰系统文件类型。因此,我搜索了我的应用名称,并从计算机中删除了旧版本。然后系统识别出我的文件后缀并立即将其打开!

但是这次我丢失了图标,但这是另一个问题:)

本文链接:https://www.f2er.com/3006691.html

大家都在问