Skip to content

Instantly share code, notes, and snippets.

@stonezhl
Last active August 3, 2019 15:05
Show Gist options
  • Save stonezhl/7a7f8c790a72001ee4751b9f1f9f084d to your computer and use it in GitHub Desktop.
Save stonezhl/7a7f8c790a72001ee4751b9f1f9f084d to your computer and use it in GitHub Desktop.
EPUBParser Class
import ZIPFoundation
class EPUBParser {
static func parseFile(at sourceURL: URL) -> EPUBBook? {
// Get the ePub's filename
let filename = sourceURL.deletingPathExtension().lastPathComponent
// The directory to save the unzipped files
let destinationURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(filename)
// Get the file manager
let fileManager = FileManager()
// Check if already unzipped
if fileManager.fileExists(atPath: destinationURL.path) == false {
do {
// Make sure the directory exists. if not, create one
try fileManager.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
// Unzip the ePub file
try fileManager.unzipItem(at: zipFileURL, to: destinationURL)
} catch {
print("Extraction of the ePub file failed with error: \(error)")
return nil
}
}
// Parse the ePub file
return EPUBBook(contentsOf: destinationURL)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment