NCViewerImageAsset.swift 2.3 KB

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