Last active
March 16, 2018 10:48
-
-
Save emarashliev/655c36d5f7f09c0656a4b60497f37e2c to your computer and use it in GitHub Desktop.
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
| struct PdfFile { | |
| var filepath: String? | |
| var file: PDFDocument? | |
| private var cacheImages = NSCache<NSString, UIImage>() | |
| var numberOfPages: Int { | |
| return file?.pdfDocument?.numberOfPages ?? 0 | |
| } | |
| init(filepath path: String?) { | |
| filepath = path | |
| file = PDFDocument.open(file: path) | |
| } | |
| mutating func page(forIndex index: Int, scaleFactor: CGFloat) -> UIImage? { | |
| guard let pdf = file else { return nil } | |
| let stringIndex = String(index) as NSString | |
| if let image = cacheImages.object(forKey: stringIndex) { | |
| return image | |
| } else { | |
| let page = index + 1 | |
| let image = pdf.render(page: page, scaleFactor: scaleFactor) | |
| if let image = image { | |
| cacheImages.setObject(image, forKey: stringIndex) | |
| } | |
| return image | |
| } | |
| } | |
| } | |
| pages = PdfFile(filepath: "/some/path") | |
| DispatchQueue.global(qos: .background).async { in | |
| let image = pages.page(forIndex: index, scaleFactor: strongSelf.scaleFactor) | |
| DispatchQueue.main.async { () -> Void in | |
| completion(image) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment