如何在Swift中压缩一个目录,而不压缩它包含的一个文件来制作ePub文件?



我正在尝试以编程方式创建一个ePub文件。我正在遵循本教程。教程中说要创建。epub容器将所有文件放入其中:

  1. 创建一个空的。zip文件,无论你喜欢什么名字(参见下面的说明,详细说明如何做到这一点)
  2. 将mimetype文件复制到zip文件中(不要对该文件使用压缩)
  3. 将上述剩下的文件和文件夹复制到zip文件*
  4. 中。
  5. 将。zip扩展名重命名为。epub

这些是该过程的最后几个步骤。我已经准备好了所有需要放入压缩包的文件。我知道这些文件是有效的,因为我使用了第三方程序(eCanCrusherMac.1.2.1)来完成这些最后的步骤,它创建的产品是一个ePub文件,可以加载到Books eReader(由Apple制造)中。

我使用下面的代码压缩所需的目录。我在这里找到了这个代码Stack Overflow

func zip(itemAtURL itemURL: URL, in destinationFolderURL: URL, zipName: String) throws {
    var error: NSError?
    var internalError: NSError?
    NSFileCoordinator().coordinate(readingItemAt: itemURL, options: [.forUploading], error: &error) { (zipUrl) in
        // zipUrl points to the zip file created by the coordinator
        // zipUrl is valid only until the end of this block, so we move the file to a temporary folder
        let finalUrl = destinationFolderURL.appendingPathComponent(zipName)
        do {
            try FileManager.default.moveItem(at: zipUrl, to: finalUrl)
        } catch let localError {
            internalError = localError as NSError
        }
    }
    
    if let error = error {
        throw error
    }
    if let internalError = internalError {
        throw internalError
    }
}

我取了这个函数给我的文件,确保它有epub扩展名,并试图使用Books应用程序打开它,但它无法加载。代码生成了一个zip文件,我可以在Finder中正常地与它交互,这样我就知道这个函数是有效的。

我认为问题出在"时间类型"上。文件被压缩。我已经采取了有效的ePub,将文件的扩展名更改为zip,解压缩,然后使用Finder重新压缩,并试图再次打开它,没有其他更改,它不起作用。正如你在这篇文章顶部的教程中所看到的,"时间类型"文件不能被压缩

这是一个Mac上的Swift应用。

我研究了不同的NSFileCoordinator。ReadingOptions和NSFileCoordinator。WritingOptions并在Stack Overflow和其他在线地方搜索,但我找不到任何关于如何在Swift中创建zip文件而不压缩zip文件中包含的文件的内容。

我可以使用ZIPFoundation打开ePub:

try FileManager.default.zipItem(
  at: bookURL,
  to: ePubURL,
  shouldKeepParent: false,
  compressionMethod: .none,
  progress: nil
)

相关内容

最新更新