How to set timeout for requests using Moya pod?

I am using Swift 3 and Moya pod.

I configured everything that I need using Basic usage , but I did not find any function or variable to set a timeout (for all requests or for a specific request).

How can i do this?

+5
source share
2 answers

haydarKarkin provided an answer to this in a GitHub comment. The following code snippets are copied directly from its comment.


You can create a custom configuration for the Moya provider by creating a custom Alamofire session manager:

import Foundation import Alamofire class DefaultAlamofireManager: Alamofire.SessionManager { static let sharedManager: DefaultAlamofireManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders configuration.timeoutIntervalForRequest = 20 // as seconds, you can set your request timeout configuration.timeoutIntervalForResource = 20 // as seconds, you can set your resource timeout configuration.requestCachePolicy = .useProtocolCachePolicy return DefaultAlamofireManager(configuration: configuration) }() } 

Then add the Alamofire user manager when declaring your provider:

 let Provider = MoyaProvider<GithubAPI>(endpointClosure: endpointClosure, manager: DefaultAlamofireManager.sharedManager, plugins: [NetworkActivityPlugin(networkActivityClosure: networkActivityClosure)]) 
+12
source

You can manage the session configuration in the session manager and select requests that use a different timeout value.

 import Foundation import Moya struct MyNetworkManager { static let provider = MoyaProvider<MyService>() static func request( target: MyService, success successCallback: @escaping (JSON) -> Void, error errorCallback: @escaping (Error) -> Void, failure failureCallback: @escaping (MoyaError) -> Void ) { //Check request switch target { case .quickAnswer: provider.manager.session.configuration.timeoutIntervalForRequest = 2 default: provider.manager.session.configuration.timeoutIntervalForRequest = Manager.default.session.configuration.timeoutIntervalForRequest } provider.request(target) { result in let url = target.path switch result { case let .success(response): do { let _ = try response.filterSuccessfulStatusCodes() let json = try JSON(response.mapJSON()) successCallback(json) } catch { errorCallback(error) } case let .failure(error): failureCallback(error) } } } } 
0
source

Source: https://habr.com/ru/post/1258418/


All Articles