2016-04-15 53 views
0

我需要在swift中解压缩一个.epub文件,以完全自己读取数据。我知道如何解析ePub的输出(我已经在python中编写了一个工作示例),但是SSZipArchive显然不会解压缩.epubs。但是,它确实可以在一个虚拟的.zip文件上正常工作。只有.epub是一个问题。据我所知,在S.O.上如何亲自实践这个问题一直没有问题。除了简单地将人们指向在Objective-C中为您提供的项目,而且这些项目有很多开销(我不明白或不需要)会破坏我需要做的事情的目的。以下是我目前的尝试。请注意,可以在以下链接(项目gutenberg)http://www.gutenberg.org/ebooks/158.epub.noimages中找到有关epub的内容,当我运行此命令时,print语句会发出:“true,true,true,false”(即文件和路径都存在,但不会解压缩):在swift中解压缩电子贺卡

import Foundation 

class EpubExtractor: NSObject, SSZipArchiveDelegate { 
    init(fileName: String) { 
     fName = fileName 
    } 

    func getEpubInfo() { 
     var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) 
     let documentsDir = paths[0] 
     let zipPath = documentsDir.stringByAppendingString("/MyZipFiles") // My folder name in document directory 
     let fileManager = NSFileManager.defaultManager() 
     let success1 = fileManager.fileExistsAtPath(zipPath) as Bool 
     if success1 == false { 
      print("no directory") 
      do { 
       try! fileManager.createDirectoryAtPath(zipPath, withIntermediateDirectories: true, attributes: nil) 
      } 
     } 
     let archivePath = zipPath.stringByAppendingString("/emma.epub") // Sample folder is going to zip with name Demo.zip 
     let success2 = fileManager.fileExistsAtPath(archivePath) as Bool 
     let destPath = zipPath.stringByAppendingString("/Hello") 
     let success3 = fileManager.fileExistsAtPath(destPath) as Bool 
     let worked = SSZipArchive.unzipFileAtPath(archivePath, toDestination: destPath, delegate:self) 
     print(success1, success2, success3, worked) 

    } 
} 

编辑

下面是用Python编写的概念证明代码中,我可以得到同样的EPUB被承认为一个zip文件并阅读其内容的容器:

import zipfile 
dir = "sampleData/epubs/" 
fileName = "emma.epub" 
print zipfile.is_zipfile(dir+fileName) # Check whether file is zip (this returns true, though in swift it fails) 

zip = zipfile.ZipFile(dir+fileName) 
txt = zip.read('META-INF/container.xml') # Print contents of container (this is what I need swift to be able to do) 
print txt # This successfully prints the container content text 

回答

3

经过许多小时的阅读后,我想出了它。如果不明显,结果是非常简单的。

“fileName.epub”文件需要重命名为“fileName.zip”。而已!

之后,SSZipArchive或Zip将文件解压到名为“fileName”文件夹(至少作为默认名称)的META-Inf,mimetype和OEBPS文件中。

希望这可以帮助任何人为此而努力。当然,如果还有其他方法可以做到这一点,请在评论中告诉我。