Skip to content

Instantly share code, notes, and snippets.

@SergLam
Last active September 21, 2019 18:04
Show Gist options
  • Save SergLam/90e5cac9f6ad054ddf1d6252ed213116 to your computer and use it in GitHub Desktop.
Save SergLam/90e5cac9f6ad054ddf1d6252ed213116 to your computer and use it in GitHub Desktop.
Moya Network Logger Pretty JSON
import Foundation
import Moya
import Alamofire
// NOTE: Custom timeout configuration
class DefaultAlamofireManager: Alamofire.SessionManager {
static let sharedManager: DefaultAlamofireManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
configuration.timeoutIntervalForRequest = 10
configuration.timeoutIntervalForResource = 10
configuration.requestCachePolicy = .useProtocolCachePolicy
return DefaultAlamofireManager(configuration: configuration)
}()
}
private let logger = NetworkLoggerPlugin(verbose: true,
requestDataFormatter: JSONRequestDataFormatter,
responseDataFormatter: JSONResponseDataFormatter)
let API = MoyaProvider<ProjectName>(manager: DefaultAlamofireManager.sharedManager,
plugins: [logger])
private func JSONResponseDataFormatter(_ data: Data) -> Data {
do {
let dataAsJSON = try JSONSerialization.jsonObject(with: data)
let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
return prettyData
} catch {
return data // fallback to original data if it can't be serialized.
}
}
private func JSONRequestDataFormatter(_ data: Data) -> String {
do {
let dataAsJSON = try JSONSerialization.jsonObject(with: data)
let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
guard let result = String(data: prettyData, encoding: String.Encoding.utf8) else {
return String(decoding: data, as: UTF8.self)
}
return result
} catch {
return String(decoding: data, as: UTF8.self)
}
}
enum ProjectName: TargetType {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment