Swift - 导入和打开自定义文件扩展名

Swift - Import and open custom file extensions

我必须在正在构建的应用程序中打开一个自定义文件,但我不确定如何操作。导入的文件仅包含其中包含 plist

的文件夹

例如 文件名.customExtension/name uuid/name.plist

如果我打开自定义文件,将另一个文件夹 "name uuid" 复制并粘贴到一个常规文件夹中,然后将其导入到应用程序中,它就可以正常工作。

例如 fileName/name uuid/name.plist

那么如何直接在应用程序中导入带有自定义扩展名的文件夹?

如果自定义文件被放入应用程序进行测试,我写了下面的代码,但它不起作用,因为我猜我没有将扩展名转换为常规文件夹,而是只是删除它.

func loadImportedFiles(){

    var fileName: String = ""
    let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    do {
        let fileUrls = try FileManager.default.contentsOfDirectory(at: documentsDirectoryURL, includingPropertiesForKeys: nil)
        for plist in fileUrls {
            let path: String = plist.path
            let file = URL(fileURLWithPath: path).lastPathComponent

            if file.contains(".CustomExtension"){
                fileName = URL(fileURLWithPath: path).deletingPathExtension().lastPathComponent
            }
        }
    } catch {
        print("error path")
    }

    var objCBool: ObjCBool = true
    let mainPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
    let folderPath = mainPath + "/Folder/\(fileName)"

    let isExist = FileManager.default.fileExists(atPath: folderPath, isDirectory: &objCBool)
    if !isExist {
        do {
            try FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print(error)
        }
    }


    let originalDataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("\(fileName).CustomExtension")
    let newDestinationPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Folder/\(fileName)")

    do { try FileManager.default.moveItem(at: originalDataFilePath!, to: newDestinationPath!)
        print("imported")
    } catch {
        print(error)
    }


}

如果有人能指导我正确的方向,那将是非常感谢!

解决方案是在 Info Plist 中使用自定义文件类型。 您需要将 "Exported Type UTIs" 和 "Document types" 添加到 Info Plist。然后您的自定义文件将被识别。

下面是我用来实现它的教程。

https://chariotsolutions.com/blog/post/importing-data-via-custom-file-types-in/