Alamofire超时无效

时间:2017-03-13 08:58:10

标签: ios swift swift3 alamofire

在我的应用程序中,我使用Alamofire进行网络请求,我创建了一个类。这是班级

class MGNetworking: NSObject{


    private class func getAlamofireManager() -> SessionManager  {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForResource = 180 // seconds
        configuration.timeoutIntervalForRequest = 180 // seconds

        let alamofireManager = Alamofire.SessionManager(configuration: configuration)

        return alamofireManager
    }

    class func requestGETURL(_ strURL: String, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void) {

        getAlamofireManager().request(strURL,method: .get).responseJSON { (responseObject) -> Void in

            if responseObject.result.isSuccess {
                let resJson = JSON(responseObject.result.value!)
                success(resJson)
            }
            if responseObject.result.isFailure {
                let error : Error = responseObject.result.error!
                failure(error)
            }
        }
    }



    class func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){

        getAlamofireManager().request(strURL, method: .post, parameters: params, encoding: URLEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in

            if responseObject.result.isSuccess {
                let resJson = JSON(responseObject.result.value!)
                success(resJson)
            }
            if responseObject.result.isFailure {
                let error : Error = responseObject.result.error!
                failure(error)
            }
        }
    }

}

我想要为我的网络请求更改超时。我创建了方法getAlamofireManager()但是当我调用此方法时,我在此处取消的请求是错误。

FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled"

当我将getAlamofireManager()更改为Alamofire.request时,它开始变得完美。

1 个答案:

答案 0 :(得分:1)

我可以假设问题与this报告的问题有关。

所以让我们重写代码:

class MGNetworking: NSObject{

 var manager: SessionManager?

 init() {
    manager = getAlamofireManager()
 }

  private class func getAlamofireManager() -> SessionManager  {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForResource = 180 // seconds
    configuration.timeoutIntervalForRequest = 180 // seconds

    let alamofireManager = Alamofire.SessionManager(configuration: configuration)

    return alamofireManager
}
}

现在使用manager而不是getAlamofireManager()作为请求