ios 如何在 alamofire 中检查互联网连接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41327325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check internet connection in alamofire?
提问by TechChain
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
我正在使用下面的代码在服务器中发出 HTTP 请求。现在我想知道它是否连接到互联网。下面是我的代码
let request = Alamofire.request(completeURL(domainName: path), method: method, parameters: parameters, encoding: encoding.value, headers: headers)
.responseJSON {
let resstr = NSString(data: import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() -> Bool {
return NetworkReachabilityManager()?.isReachable ?? false
}
}
.data!, encoding: String.Encoding.utf8.rawValue)
print("error is \(resstr)")
if if Connectivity.isConnectedToInternet() {
print("Yes! internet is available.")
// do some tasks..
}
.result.isFailure {
self.failure("Network")
print("API FAILED 4")
return
}
guard let result = import Foundation
import Alamofire
class Connectivity {
class var isConnectedToInternet:Bool {
return NetworkReachabilityManager()?.isReachable ?? false
}
}
.result.value else {
self.unKnownError()
self.failure("")
print("API FAILED 3")
return
}
self.handleSuccess(JSON(result))
}
回答by abhimuralidharan
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.
对于 swift 3.1 和 Alamofire 4.4,我创建了一个名为Connectivity
. 使用NetworkReachabilityManager
从类Alamofire
和configure
该isConnectedToInternet()
方法根据自己的需要。
if Connectivity.isConnectedToInternet {
print("Yes! internet is available.")
// do some tasks..
}
Usage:
用法:
Alamofire.request(.POST, url).responseJSON { response in
switch response.result {
case .Success(let json):
// internet works.
case .Failure(let error):
if let err = error as? NSURLError where err == .NotConnectedToInternet {
// no internet connection
} else {
// other failures
}
}
}
EDIT:Since swift is encouraging computed properties, you can change the above function like:
编辑:由于 swift 鼓励计算属性,您可以更改上述函数,如:
Alamofire.upload(multipartFormData: { multipartFormData in
}, to: URL, method: .post,headers: nil,
encodingCompletion: { (result) in
switch result {
case .success( _, _, _): break
case .failure(let encodingError ):
print(encodingError)
if let err = encodingError as? URLError, err.code == .notConnectedToInternet {
// no internet connection
print(err)
} else {
// other failures
}
}
})
and use it like:
并使用它:
let networkReachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")
func checkForReachability() {
self.networkReachabilityManager?.listener = { status in
print("Network Status: \(status)")
switch status {
case .notReachable:
//Show error here (no internet connection)
case .reachable(_), .unknown:
//Hide error here
}
}
self.networkReachabilityManager?.startListening()
}
//How to Use : Just call below function in required class
if checkForReachability() {
print("connected with network")
}
回答by MAhipal Singh
Swift 2.3
斯威夫特 2.3
let reachabilityManager = NetworkReachabilityManager()
reachabilityManager?.startListening()
reachabilityManager?.listener = { _ in
if let isNetworkReachable = self.reachabilityManager?.isReachable,
isNetworkReachable == true {
//Internet Available
} else {
//Internet Not Available"
}
}
Swift 3.0
斯威夫特 3.0
Alamofire.upload(multipartFormData: { multipartFormData in
for (key,value) in parameters {
multipartFormData.append((value).data(using: .utf8)!, withName: key)
}
multipartFormData.append(self.imageData!, withName: "image" ,fileName: "image.jpg" , mimeType: "image/jpeg")
}, to:url)
{ (result) in
switch result{
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
if let statusCode = response.response?.statusCode{
if(statusCode == 201){
//internet available
}
}else{
//internet not available
}
}
case .failure(let encodingError):
print(encodingError)
}
}
Using NetworkReachabilityManager
使用 NetworkReachabilityManager
import AlamofireNetworkActivityIndicator
private let manager = NetworkReachabilityManager(host: "www.apple.com")
func isNetworkReachable() -> Bool {
return manager?.isReachable ?? false
}
回答by Parth Adroja
For Swift 3/4,
对于 Swift 3/4,
In Alamofire, there is a class called NetworkReachabilityManager
which can be used to observer or check if internet is available or not.
在 Alamofire 中,有一个名为的类NetworkReachabilityManager
,可用于观察或检查互联网是否可用。
func isConnectedToNetwork()-> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
class RequestInterceptor : RequestAdapter{
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
let reachable = NetworkReachabilityManager()?.isReachable ?? false
if !reachable{
throw NSError.NoInternet
}
var nUrlRequest = urlRequest
// modify request if needed
return nUrlRequest
}
}
extension NSError {
static func createWithLocalizedDesription(withCode code:Int = 204,localizedDescription:String) -> NSError{
return NSError(domain: "<your bundle id>", code:code, userInfo: [NSLocalizedDescriptionKey : localizedDescription])
}
static var NoInternet : NSError {
return createWithLocalizedDesription(withCode: -1009,localizedDescription:"Please check your internet connection")
}
}
.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
//Commented code only work upto iOS Swift 2.3
// let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
//
// SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer(let sessionManager = Alamofire.SessionManager(configuration: configuration)
sessionManager.adapter = RequestInterceptor()
))
// }
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
// Call api method
func callApi(){
if isConnectedToNetwork() { // Network Connection status
// Call your request here
}else{
//"Your Internet connection is not active at this time."
}
}
Here, listener will get called every time when there is changes in state of internet. You can handle it as you would like.
在这里,每当互联网状态发生变化时,侦听器都会被调用。你可以随心所欲地处理它。
回答by Nupur Sharma
If Alamofire.upload resultreturns success then below is the way to check for internet availibility while uploading an image:
如果 Alamofire.upload结果返回成功,那么下面是上传图像时检查互联网可用性的方法:
##代码##回答by Umair Afzal
If you goto NetworkReachabilityManager.swift
you will see this
如果你转到NetworkReachabilityManager.swift
你会看到这个
/// Whether the network is currently reachable. public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
/// 当前网络是否可达。public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
So I have written this in my APIhandlerClass
所以我在我的 APIhandlerClass 中写了这个
##代码##So this tells me the status of network.
所以这告诉我网络的状态。
回答by MAhipal Singh
回答by Eoin Norris
In general if you can get the internet offline information from the actual call, its better than reachability. You can be certain that the actual API call has failed because the internet is down. If you test for reachability before you call an API and it fails then all you know is that when the test was done the internet was offline ( or Apple was down), you don't know that when you makethe call the internet will be offline. You might think it is a matter of milliseconds after the reachability call returns, or you retrieved the stored value, but thats in fact non deterministic. The OS might have scheduled some arbitrary number of threads before reachability returns its values in its closure, or updates whatever global you are storing.
一般来说,如果您可以从实际通话中获得互联网离线信息,则比可达性更好。您可以确定实际 API 调用已失败,因为 Internet 已关闭。如果您测试您的可达性调用API之前,然后它发生故障,所有你知道的是,当有人做过试验,上网是脱机(或苹果下跌了),你不知道,当你做出呼叫的互联网将成为离线。您可能认为这是在可达性调用返回后的几毫秒内,或者您检索了存储的值,但实际上这是不确定的。在可达性在其闭包中返回其值之前,操作系统可能已经调度了一些任意数量的线程,或者更新了您存储的任何全局变量。
And reachability has historically had bugs in its own code.
并且可达性历来在其自己的代码中存在错误。
This isn't to say that you shouldn't use alamofire's NetworkReachabilityManager to change your UI, listen to it and update all the UI components.
这并不是说您不应该使用 alamofire 的 NetworkReachabilityManager 来更改您的 UI、聆听它并更新所有 UI 组件。
But if you have reason to call an API, at that API layer the test for reachability is redundant, or possibly will cause some subtle bugs.
但是如果你有理由调用一个 API,在那个 API 层,可达性测试是多余的,或者可能会导致一些微妙的错误。
回答by Aromal Sasidharan
Using RequestAdapter
class of alamofire and throw error when no internet connectivity
使用RequestAdapter
alamofire 类并在没有互联网连接时抛出错误
##代码##
Now set the adapter to Alamofire Session Manager
现在将适配器设置为 Alamofire Session Manager
Now each time when You create Alamofire Request, catch the error in DataResponse. This mechanism will act common to all request
现在,每次您创建Alamofire Request 时,都会在 DataResponse 中捕获错误。此机制将适用于所有请求