ActionExecutor.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import Foundation
  2. import UIKit
  3. struct ActionExecutor {
  4. private static let tag = "ActionExecutor"
  5. static func execute(_ action: MessageAction) {
  6. Log.d(tag, "Executing user action", action)
  7. switch action.action {
  8. case "view":
  9. if let url = URL(string: action.url ?? "") {
  10. open(url: url)
  11. } else {
  12. Log.w(tag, "Unable to parse action URL", action)
  13. }
  14. case "http":
  15. http(action)
  16. default:
  17. Log.w(tag, "Action \(action.action) not supported", action)
  18. }
  19. }
  20. private static func http(_ action: MessageAction) {
  21. guard let actionUrl = action.url, let url = URL(string: actionUrl) else {
  22. Log.w(tag, "Unable to execute HTTP action, no or invalid URL", action)
  23. return
  24. }
  25. let method = action.method ?? "POST" // POST is the default!!
  26. let body = action.body ?? ""
  27. Log.d(tag, "Performing HTTP \(method) \(url)")
  28. var request = URLRequest(url: url)
  29. request.httpMethod = method
  30. action.headers?.forEach { key, value in
  31. request.setValue(value, forHTTPHeaderField: key)
  32. }
  33. if !["GET", "HEAD"].contains(method) {
  34. request.httpBody = body.data(using: .utf8)
  35. }
  36. URLSession.shared.dataTask(with: request) { (data, response, error) in
  37. guard error == nil else {
  38. Log.e(self.tag, "Error performing HTTP \(method)", error!)
  39. return
  40. }
  41. Log.d(self.tag, "HTTP \(method) succeeded", response)
  42. }.resume()
  43. }
  44. private static func open(url: URL) {
  45. Log.d(tag, "Opening URL \(url)")
  46. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  47. }
  48. }