NCViewerImageAsset.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 metadata: tableMetadata?
  16. private override init() { }
  17. public init(url: URL) {
  18. self.url = url
  19. }
  20. public init(url: URL, caption: String?) {
  21. self.url = url
  22. }
  23. public init(image: UIImage) {
  24. self.image = image
  25. }
  26. public init(metadata: tableMetadata) {
  27. self.metadata = metadata
  28. }
  29. public init(image: UIImage, caption: String?) {
  30. self.image = image
  31. }
  32. func download(completion:@escaping(_ success: Bool?) -> Void) -> URLSessionDataTask? {
  33. return NCViewerImageAsset.download(url: url) { (success, image, type) in
  34. self.image = image
  35. if let type = type {
  36. self.type = type
  37. }
  38. completion(success)
  39. }
  40. }
  41. static func download(url: URL?, completion:@escaping(_ success: Bool?, _ image: UIImage?, _ type: NCViewerImageAsset.ImageType?) -> Void) -> URLSessionDataTask? {
  42. guard let url = url else {
  43. completion(false, nil, nil)
  44. return nil
  45. }
  46. let dataTask = URLSession.shared.dataTask(with: url) { data, response, error in
  47. guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
  48. let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
  49. let data = data, error == nil,
  50. var image = UIImage(data: data)
  51. else {
  52. DispatchQueue.main.async { completion(false, nil, nil) }
  53. return
  54. }
  55. let type: NCViewerImageAsset.ImageType? = ImageType.from(mimeType: mimeType)
  56. /*
  57. if type == .gif, let gif = UIImage.gif(data: data) {
  58. image = gif
  59. }
  60. */
  61. DispatchQueue.main.async { completion(true, image, type) }
  62. }
  63. dataTask.resume()
  64. return dataTask
  65. }
  66. }