Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.92 KB | None | 0 0
  1. import Foundation
  2.  
  3. public class NetworkLogger {
  4. public static let shared = NetworkLogger()
  5.  
  6. public func startLogging() {
  7. let notificationCenter = NotificationCenter.default
  8.  
  9. notificationCenter.addObserver(
  10. self,
  11. selector: #selector(logRequestInfo),
  12. name: Notification.Name.Task.DidResume,
  13. object: nil
  14. )
  15.  
  16. notificationCenter.addObserver(
  17. self,
  18. selector: #selector(logRequestInfo),
  19. name: Notification.Name.Task.DidComplete,
  20. object: nil
  21. )
  22. }
  23.  
  24. @objc private func logRequestInfo(_ notification: Notification) {
  25. guard let userInfo = notification.userInfo,
  26. let task = userInfo[Notification.Key.Task] as? URLSessionTask,
  27. let request = task.originalRequest,
  28. let httpMethod = request.httpMethod
  29. else { return }
  30. let requestPath = [request.url?.path, request.url?.query].compactMap { $0 }.joined(separator: "?")
  31.  
  32. if let response = task.response as? HTTPURLResponse {
  33. let message = components(
  34. httpMethod: httpMethod,
  35. requestPath: requestPath,
  36. data: userInfo[Notification.Key.ResponseData] as? Data,
  37. statusCode: response.statusCode
  38. )
  39. print("Finished network request: \(message)")
  40. } else if let error = task.error {
  41. let message = components(
  42. httpMethod: httpMethod,
  43. requestPath: requestPath,
  44. data: userInfo[Notification.Key.ResponseData] as? Data
  45. )
  46. print("Finished network request: \(message) with errors: \(error)")
  47. } else {
  48. let message = components(
  49. httpMethod: httpMethod,
  50. requestPath: requestPath,
  51. data: task.originalRequest?.httpBody
  52. )
  53. print("Started network request: \(message)")
  54. }
  55. }
  56. func components(httpMethod: String, requestPath: String, data: Data?, statusCode: Int? = nil) -> String {
  57. return [
  58. "AF request",
  59. "<\(httpMethod)",
  60. statusCode?.description,
  61. "\(requestPath)>",
  62. json(from: data)
  63. ]
  64. .compactMap { $0 }
  65. .joined(separator: " ")
  66. }
  67.  
  68. func json(from data: Data?) -> String? {
  69. let emptyArray = "[]"
  70. let emptyDictionary = "{}"
  71. let converted: String
  72. if let data = data {
  73. converted = String(data: data, encoding: .utf8) ?? emptyDictionary
  74. } else {
  75. converted = emptyDictionary
  76. }
  77. if [emptyDictionary, emptyArray].contains(converted) {
  78. return "HTTPBody: \(converted);"
  79. } else {
  80. return "HTTPBody:\n" + converted
  81. }
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement