如何检查alamofire中的互联网连接? [英] How to check internet connection in alamofire?
本文介绍了如何检查alamofire中的互联网连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用下面的代码在服务器中发出HTTP请求。现在我想知道它是否连接到互联网。下面是我的代码
I am using below code for making HTTP request in server.Now I want to know whether it is connected to internet or not. Below is my code
let request = Alamofire.request(completeURL(domainName: path), method: method, parameters: parameters, encoding: encoding.value, headers: headers)
.responseJSON {
let resstr = NSString(data: $0.data!, encoding: String.Encoding.utf8.rawValue)
print("error is \(resstr)")
if $0.result.isFailure {
self.failure("Network")
print("API FAILED 4")
return
}
guard let result = $0.result.value else {
self.unKnownError()
self.failure("")
print("API FAILED 3")
return
}
self.handleSuccess(JSON(result))
}
推荐答案
适用于swift 3.1和Alamofire 4.4 ,我创建了一个名为 Connectivity
的快速类。使用 NetworkReachabilityManager
类 Alamofire
和配置
isConnectedToInternet()
方法根据您的需要。
For swift 3.1 and Alamofire 4.4 ,I created a swift class called Connectivity
. Use NetworkReachabilityManager
class from Alamofire
and configure
the isConnectedToInternet()
method as per your need.
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
用法:
if Connectivity.isConnectedToInternet() {
print("Yes! internet is available.")
// do some tasks..
}
编辑:
由于swift鼓励计算属性,您可以更改以上函数如:
Since swift is encouraging computed properties, you can change the above function like:
import Foundation
import Alamofire
class Connectivity {
class var isConnectedToInternet:Bool {
return NetworkReachabilityManager()!.isReachable
}
}
并使用它:
if Connectivity.isConnectedToInternet {
print("Yes! internet is available.")
// do some tasks..
}
这篇关于如何检查alamofire中的互联网连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文