Last active
August 3, 2019 15:05
-
-
Save stonezhl/7a7f8c790a72001ee4751b9f1f9f084d to your computer and use it in GitHub Desktop.
EPUBParser Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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