Skip to content

Instantly share code, notes, and snippets.

@emarashliev
Last active March 16, 2018 10:48
Show Gist options
  • Select an option

  • Save emarashliev/655c36d5f7f09c0656a4b60497f37e2c to your computer and use it in GitHub Desktop.

Select an option

Save emarashliev/655c36d5f7f09c0656a4b60497f37e2c to your computer and use it in GitHub Desktop.
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