NCViewerImageAsset.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import UIKit
  2. class NCViewerImageAsset: NSObject {
  3. public enum ImageType {
  4. case jpg
  5. case gif
  6. static func from(mimeType: String) -> ImageType? {
  7. if mimeType.contains("gif") { return .gif
  8. } else if mimeType.contains("jpg") { return .jpg }
  9. return nil
  10. }
  11. }
  12. public var url: URL?
  13. // public var image: UIImage?
  14. public var type: ImageType?
  15. public var caption: String?
  16. public var metadata: tableMetadata?
  17. private override init() { }
  18. public init(url: URL) {
  19. self.url = url
  20. }
  21. public init(url: URL, caption: String?) {
  22. self.url = url
  23. self.caption = caption
  24. }
  25. public init(metadata: tableMetadata) {
  26. self.metadata = metadata
  27. self.caption = metadata.fileNameView
  28. }
  29. func download(completion:@escaping(_ success: Bool?) -> Void) -> URLSessionDataTask? {
  30. return NCViewerImageAsset.download(url: url) { (success, image, type) in
  31. // self.image = image
  32. if let type = type {
  33. self.type = type
  34. }
  35. completion(success)
  36. }
  37. }
  38. static func download(url: URL?, completion:@escaping(_ success: Bool?, _ image: UIImage?, _ type: NCViewerImageAsset.ImageType?) -> Void) -> URLSessionDataTask? {
  39. guard let url = url else {
  40. completion(false, nil, nil)
  41. return nil
  42. }
  43. let dataTask = URLSession.shared.dataTask(with: url) { data, response, error in
  44. guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
  45. let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
  46. let data = data, error == nil,
  47. var image = UIImage(data: data)
  48. else {
  49. DispatchQueue.main.async { completion(false, nil, nil) }
  50. return
  51. }
  52. let type: NCViewerImageAsset.ImageType? = ImageType.from(mimeType: mimeType)
  53. if type == .gif, let gif = UIImage.gif(data: data) {
  54. image = gif
  55. }
  56. DispatchQueue.main.async { completion(true, image, type) }
  57. }
  58. dataTask.resume()
  59. return dataTask
  60. }
  61. }