Search code examples
iosswiftmoya

How can I set timeout for requests using Moya pod?


I'm using Swift 3 and the Moya pod.

I configured everything I needed using the Basic Usage, but I didn't find any function or variable that I can set the timeout (for every requests or for a specific request).

How can I do this?


Solution

  • haydarKarkin has provided an answer to this in a comment on GitHub. The code snippets below are copied directly from his comment.


    You can create a custom configuration for a 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 include the custom Alamofire Manager when declaring your Provider:

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