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