如何检查alamofire中的互联网连接?

时间:2016-12-26 06:37:12

标签: ios swift alamofire reachability

我使用下面的代码在服务器中发出HTTP请求。现在我想知道它是否连接到互联网。以下是我的代码

  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))
    }

8 个答案:

答案 0 :(得分:70)

对于swift 3.1和Alamofire 4.4 ,我创建了一个名为Connectivity的快速类。根据您的需要,使用NetworkReachabilityManager中的Alamofire课程和configure isConnectedToInternet()方法。

import Foundation
import Alamofire

class Connectivity {
    class func isConnectedToInternet() -> Bool {
        return NetworkReachabilityManager()?.isReachable ?? false
    }
}

用法:

if Connectivity.isConnectedToInternet() {
        print("Yes! internet is available.")
        // do some tasks..
 }

<强> 编辑: 由于swift鼓励计算属性,您可以更改上述函数,如:

import Foundation
import Alamofire
class Connectivity {
    class var isConnectedToInternet:Bool {
        return NetworkReachabilityManager()?.isReachable ?? false
    }
}

并使用它:

if Connectivity.isConnectedToInternet {
        print("Yes! internet is available.")
        // do some tasks..
 }

答案 1 :(得分:18)

  

Swift 2.3

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
        }
    }
}
  

Swift 3.0

  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
            }

        }
    })
  

使用NetworkReachabilityManager

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")
}

答案 2 :(得分:11)

对于Swift 3/4,

在Alamofire中,有一个名为b的课程,可用于观察或检查互联网是否可用。

bar

在这里,每当互联网状态发生变化时,都会调用监听器。你可以按照自己的意愿处理它。

答案 3 :(得分:2)

如果你转到NetworkReachabilityManager.swift,你会看到这个

  

///网络目前是否可以访问。       public var isReachable:Bool {return isReachableOnWWAN || isReachableOnEthernetOrWiFi}

所以我在我的APIhandlerClass

中写了这个
import AlamofireNetworkActivityIndicator

private let manager = NetworkReachabilityManager(host: "www.apple.com")

func isNetworkReachable() -> Bool {
    return manager?.isReachable ?? false
}

所以这告诉我网络的状态。

答案 4 :(得分:1)

  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) {
        $0.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($0))
    //    }

    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."
        }
    }

答案 5 :(得分:0)

如果Alamofire.upload 结果返回成功,则下方是在上传图片时检查互联网可用性的方法:

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)

                }

            }

答案 6 :(得分:0)

使用RequestAdapter类alamofire并在没有互联网连接时抛出错误

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")
}

}

现在将适配器设置为Alamofire Session Manager

let sessionManager = Alamofire.SessionManager(configuration: configuration)

sessionManager.adapter = RequestInterceptor()

现在每次创建 Alamofire请求时,都会捕获DataResponse中的错误。这种机制对所有请求都是通用的

答案 7 :(得分:0)

通常,如果您可以从实际通话中获得Internet脱机信息,则它比可达性要好。您可以确定实际的API调用已失败,因为Internet断开了。如果您在调用API之前测试了可访问性,但失败了,那么您所知道的是,测试完成后,Internet处于脱机状态(或Apple处于关闭状态),您不知道 make 互联网通话将离线。您可能会以为可达性调用返回后,或者您检索了存储的值后仅几毫秒,但这实际上是不确定的。在可达性在关闭时返回其值或更新您正在存储的任何全局变量之前,操作系统可能已调度了任意数量的线程。

从历史上看,可到达性在其自己的代码中存在错误。

这并不是说您不应该使用alamofire的NetworkReachabilityManager更改UI,聆听并更新所有UI组件。

但是,如果您有理由调用某个API,则在该API层进行的可达性测试是多余的,否则可能会导致一些细微的错误。