Clipboard.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import Foundation
  2. import Capacitor
  3. public class Clipboard {
  4. enum ContentType: Int {
  5. case string
  6. case url
  7. case image
  8. }
  9. public enum ClipboardError: LocalizedError {
  10. case invalidURL, invalidImage
  11. public var errorDescription: String? {
  12. switch self {
  13. case .invalidURL:
  14. return "Unable to form URL"
  15. case .invalidImage:
  16. return "Unable to encode image"
  17. }
  18. }
  19. }
  20. func write(content: String, ofType type: ContentType) -> Result<Void, Error> {
  21. switch type {
  22. case ContentType.string:
  23. UIPasteboard.general.string = content
  24. return .success(())
  25. case ContentType.url:
  26. if let url = URL(string: content) {
  27. UIPasteboard.general.url = url
  28. return .success(())
  29. } else {
  30. return .failure(ClipboardError.invalidURL)
  31. }
  32. case ContentType.image:
  33. if let data = Data.capacitor.data(base64EncodedOrDataUrl: content), let image = UIImage(data: data) {
  34. CAPLog.print("Loaded image", image.size.width, image.size.height)
  35. UIPasteboard.general.image = image
  36. return .success(())
  37. } else {
  38. return .failure(ClipboardError.invalidImage)
  39. }
  40. }
  41. }
  42. func read() -> [String: Any] {
  43. if let stringValue = UIPasteboard.general.string {
  44. return [
  45. "value": stringValue,
  46. "type": "text/plain"
  47. ]
  48. }
  49. if let url = UIPasteboard.general.url {
  50. return [
  51. "value": url.absoluteString,
  52. "type": "text/plain"
  53. ]
  54. }
  55. if let image = UIPasteboard.general.image {
  56. let data = image.pngData()
  57. if let base64 = data?.base64EncodedString() {
  58. return [
  59. "value": "data:image/png;base64," + base64,
  60. "type": "image/png"
  61. ]
  62. }
  63. }
  64. return [:]
  65. }
  66. }