Moya+Alamofire POST request is getting timeout when switching between apps or going into background

Viewed 765

I am calling an API before switching app or going into background but when I switch to foreground within 5-10 seconds that API request gets timedout. I am using Moya+Alaomofile with RxSwift. I have tried increasing the SessionConfiguration timeout but it is not helping and the API is working fine for Android and Web. Below is the code I am using:

APIOrder.provider.rx.request(.placeOrder(orderDetails: orderDetails))
            .map { any -> SROrderData in
                do {
                    let decoder = JSONDecoder()
                    guard let paymentDataModel = try decoder.decode(Safe<SRPaymentDataResponse>.self, from: any.data).value else {
                        throw ApiError.parseError
                    }
                    return paymentDataModel.data
                } catch {
                    throw try throwAPIError(data: any.data)
                }
        }

static var provider = MoyaProvider<MoyaOrder>(manager: DefaultAlamofireManager.sharedManager)

class DefaultAlamofireManager: Alamofire.SessionManager {
    static let sharedManager: DefaultAlamofireManager = {
        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
        configuration.timeoutIntervalForRequest = 120 // as seconds, you can set your request timeout
        configuration.timeoutIntervalForResource = 120 // as seconds, you can set your resource timeout
        configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
        configuration.shouldUseExtendedBackgroundIdleMode = true
        if #available(iOS 13.0, *) {
            configuration.allowsExpensiveNetworkAccess = true
        }
        configuration.networkServiceType = .background
        configuration.waitsForConnectivity = true
        return DefaultAlamofireManager(configuration: configuration)
    }()
}
1 Answers

Currently I looked around in Moya Github, but I didn't find the appropriate solution. So in order to solve it, I saved all my requests in a stack and when the App is active again, I stop the current requests and restart them again.

Related