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属性来为每个请求设置超时时间。

  • 相关阅读:
    BZOJ 1907: 树的路径覆盖
    BZOJ 1295: [SCOI2009]最长距离
    BZOJ 1303: [CQOI2009]中位数图
    BZOJ 1468: Tree
    BZOJ 3784: 树上的路径
    BZOJ 2006: [NOI2010]超级钢琴
    BZOJ 1831: [AHOI2008]逆序对
    BZOJ 2521: [Shoi2010]最小生成树
    HDU 6685 Rikka with Coin (枚举 思维)
    HDU 6659 Acesrc and Good Numbers (数学 思维)
  • 原文地址:https://www.cnblogs.com/iOSDeng/p/9843689.html
Copyright © 2011-2022 走看看