我正在Swift 3.0
使用Alamofire 4
。我正在使用单例网络类向服务器发出API
个请求。当没有互联网时,Alamofire需要大约30秒才能完成关闭并运行故障处理程序。这是我的代码:
func performRequest(_ url:String,completionHandler:@escaping (_ Success:Bool,AnyObject?) -> Void) {
Alamofire.request(url).validate().responseJSON { response in
if response.result.isSuccess { //Request was successful
self.errorCount = 0
completionHandler(true,response.result.value as AnyObject?)
} else {
print("failure occured")
self.setNoInternetDialogAppear()
}
}
}
我也尝试使用此代码设置超时,但它没有效果:
`Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 2000`
我最近从Swift 2.2和Alamofire 3迁移了我的代码,并且从那时起才开始发生。 TIA
答案 0 :(得分:0)
var alamoFireManager = Alamofire.SessionManager.default
self.alamoFireManager.session.configuration.timeoutIntervalForRequest = 2000
....
self.alamoFireManager.request(...)
使用变量工作。
答案 1 :(得分:0)
在启动alamofire请求之前测试网络连接会更好。试试这个功能。
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
答案 2 :(得分:0)
我仍在试图理解Alamofire为什么花这么长时间才能在没有互联网的情况下完成请求,但是如果您只想更改超时间隔,则可以使用URLSessionConfiguration对象。
init(interceptor: RequestInterceptor) {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = HTTPHeaders.default.dictionary
configuration.timeoutIntervalForRequest = 15
self.session = Session(configuration: configuration, interceptor: interceptor)
}