Actions.swift 909 B

1234567891011121314151617181920212223242526272829
  1. import Foundation
  2. struct Actions {
  3. static let shared = Actions()
  4. private let tag = "Actions"
  5. private let supportedActions = ["view", "http"]
  6. func parse(_ actions: String?) -> [Action]? {
  7. guard let actions = actions, actions != "",
  8. let data = actions.data(using: .utf8) else { return nil }
  9. do {
  10. return try JSONDecoder().decode([Action].self, from: data)
  11. .filter { supportedActions.contains($0.action) }
  12. } catch {
  13. Log.e(tag, "Unable to parse actions: \(error.localizedDescription)", error)
  14. return nil
  15. }
  16. }
  17. func encode(_ actions: [Action]?) -> String {
  18. guard let actions = actions else { return "" }
  19. if let actionsData = try? JSONEncoder().encode(actions) {
  20. return String(data: actionsData, encoding: .utf8) ?? ""
  21. }
  22. return ""
  23. }
  24. }