Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

ios - How to check internet connection in alamofire?

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))
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Usage:

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

EDIT: 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 ?? false
    }
}

and use it like:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...