zoukankan      html  css  js  c++  java
  • swift 4.0 ,Alamofire请求框架添加超时时间

    先上代码,再作解释

    /// 网络请求框架 GET POST/// - Parameters:
        ///   - url: url
        ///   - method: GET POST
        ///   - parameters: 参数
        ///   - completion: 完成回调
        func request(url: URLConvertible,
                     method: HTTPMethod = .get ,
                     timeoutInterval: TimeInterval = 10,
                     headers: HTTPHeaders? = nil,
                     parameters: Parameters? = nil,
                     completion: @escaping (_ value: Any?,_ isSuccess: Bool)->()) {
            //
            guard var myURLRequest = try? URLRequest(url: url, method: method, headers: headers) else{
                print("错误的URLRequest")
                return
            }
            guard let encodedURLRequest = try? URLEncoding.default.encode(myURLRequest, with: parameters) else{
                print("错误的URLEncoding")
                return
            }
            //
            myURLRequest.timeoutInterval = timeoutInterval
            //auth
            SessionManager.default.delegate.sessionDidReceiveChallenge = {
                session,challenge in
                return (URLSession.AuthChallengeDisposition.useCredential,URLCredential(trust:challenge.protectionSpace.serverTrust!))
            }
            //
            Alamofire.request(encodedURLRequest).responseJSON { (response) in
                //
                if response.result.isSuccess {
                    completion(response.result.value,true)
                }else {
                    print("错误的:")
                    print(url)
                    print(response.error!)
                    completion(nil,false)
                }
            }
    
    
        }

    Alamofire虽然可以设置总超时时间,但是那种必须要设置sessionManager,而且不能为单一请求,单独设置请求时间。所以来设置URLRequest,通过设置timeoutInterval属性来为每个请求设置超时时间。

  • 相关阅读:
    RabbitMQ简介、特性、使用场景、安装、启动与关闭
    mybatis的工作原理
    bzoj2119 股市的预测
    Noi2014 购票
    51Nod 算法马拉松22 开黑记
    COGS2485 从零开始的序列
    Codeforces Round #402 (Div.2)
    BestCoder Round #92
    COGS2294 释迦
    bzoj4764 弹飞大爷
  • 原文地址:https://www.cnblogs.com/iOSDeng/p/9843689.html
Copyright © 2011-2022 走看看