How can I set timeout for requests using Moya pod?

@askielboe's great answer updated for Alamofire 5:

class DefaultAlamofireSession: Alamofire.Session {
    static let shared: DefaultAlamofireSession = {
        let configuration = URLSessionConfiguration.default
        configuration.headers = .default
        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 DefaultAlamofireSession(configuration: configuration)
    }()
}

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)])

Tags:

Ios

Swift

Moya