Guest User

Untitled

a guest
Mar 24th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. struct PdfFile {
  2. var filepath: String?
  3. var file: PDFDocument?
  4. private var cacheImages = NSCache<NSString, UIImage>()
  5.  
  6. var numberOfPages: Int {
  7. return file?.pdfDocument?.numberOfPages ?? 0
  8. }
  9.  
  10. init(filepath path: String?) {
  11. filepath = path
  12. file = PDFDocument.open(file: path)
  13. }
  14.  
  15. mutating func page(forIndex index: Int, scaleFactor: CGFloat) -> UIImage? {
  16. guard let pdf = file else { return nil }
  17. let stringIndex = String(index) as NSString
  18. if let image = cacheImages.object(forKey: stringIndex) {
  19. return image
  20. } else {
  21. let page = index + 1
  22. let image = pdf.render(page: page, scaleFactor: scaleFactor)
  23. if let image = image {
  24. cacheImages.setObject(image, forKey: stringIndex)
  25. }
  26. return image
  27. }
  28. }
  29. }
  30.  
  31.  
  32. pages = PdfFile(filepath: "/some/path")
  33.  
  34. DispatchQueue.global(qos: .background).async { in
  35. let image = pages.page(forIndex: index, scaleFactor: strongSelf.scaleFactor)
  36. DispatchQueue.main.async { () -> Void in
  37. completion(image)
  38. }
  39. }
Add Comment
Please, Sign In to add comment