Last active
September 21, 2019 18:04
-
-
Save SergLam/90e5cac9f6ad054ddf1d6252ed213116 to your computer and use it in GitHub Desktop.
Moya Network Logger Pretty JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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