Attachment.swift 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import Foundation
  2. import SwiftUI
  3. import UIKit
  4. let attachmentTag = "Attachment"
  5. extension Attachment {
  6. func sizeString() -> String? {
  7. guard size > 0 else { return nil }
  8. return formatSize(size)
  9. }
  10. func isDownloaded() -> Bool {
  11. return contentUrl?.isEmpty == false
  12. }
  13. func isExpired() -> Bool {
  14. return timeExpired(self.expires)
  15. }
  16. func expiresString() -> String {
  17. if (self.isExpired()) {
  18. return "Expired"
  19. }
  20. let date = NSDate(timeIntervalSince1970: TimeInterval(self.expires))
  21. let formatter = RelativeDateTimeFormatter()
  22. return "Expires \(formatter.localizedString(for: date as Date, relativeTo: Date()))"
  23. }
  24. func asImage() -> Image? {
  25. guard let contentUrl = contentUrl else { return nil }
  26. let url = URL(fileURLWithPath: contentUrl)
  27. do {
  28. let data = try Data(contentsOf: url)
  29. let image = try UIImage(data: data).orThrow("Cannot load image from data")
  30. Log.d(attachmentTag, "Successfulluy loaded image attachment from \(contentUrl), URL: \(url)")
  31. return Image(uiImage: image)
  32. } catch {
  33. Log.w(attachmentTag, "Error loading image attachment from \(contentUrl), URL: \(url)", error)
  34. return nil
  35. }
  36. }
  37. }