有没有办法检查是否可以使用Swift连接互联网?
我知道有很多第三方库可以做到这一点,但它们都是用Objective-C编写的。我正在寻找一个Swift替代品。
答案 0 :(得分:220)
正如评论中所提到的,尽管可以在Swift中使用Objective-C库,但我想要一个更纯粹的Swift解决方案。现有的Apple Reachability类和其他第三方库似乎太复杂了,我无法翻译成Swift。我用Google搜索了一些,我遇到了这个article,它显示了一种检查网络可用性的简单方法。我打算将其转换为Swift。我点击了很多snags,但感谢StackOverflow的Martin R,我设法解决了这些问题,最后在Swift中得到了一个可行的解决方案。这是代码。
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return isReachable && !needsConnection
}
}
对于Swift> 3.0
public class Reachability {
public 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
}
if flags.isEmpty {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
}
适用于3G和WiFi连接。我还通过一个工作示例将其上传到我的GitHub。
答案 1 :(得分:16)
我给你更好的方式......
您必须使用此代码
创建一个类 import Foundation
public class Reachability {
class func isConnectedToNetwork()->Bool{
var Status:Bool = false
let url = NSURL(string: "http://google.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
var response: NSURLResponse?
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
Status = true
}
}
return Status
}
}
然后,您可以使用以下代码检查项目中任何位置的互联网连接:
if Reachability.isConnectedToNetwork() == true {
println("Internet connection OK")
} else {
println("Internet connection FAILED")
}
非常简单!
*这种方式基于Vikram Pote回答!
答案 2 :(得分:14)
适用于Swift 3.1(iOS 10.1)
如果您想区分网络类型(即WiFi或WWAN):
您可以使用:
func checkWiFi() -> Bool {
let networkStatus = Reachability().connectionStatus()
switch networkStatus {
case .Unknown, .Offline:
return false
case .Online(.WWAN):
print("Connected via WWAN")
return true
case .Online(.WiFi):
print("Connected via WiFi")
return true
}
}
以下是区分网络类型的整个Reachability-Class:
import Foundation
import SystemConfiguration
import UIKit
import SystemConfiguration.CaptiveNetwork
public let ReachabilityStatusChangedNotification = "ReachabilityStatusChangedNotification"
public enum ReachabilityType: CustomStringConvertible {
case WWAN
case WiFi
public var description: String {
switch self {
case .WWAN: return "WWAN"
case .WiFi: return "WiFi"
}
}
}
public enum ReachabilityStatus: CustomStringConvertible {
case Offline
case Online(ReachabilityType)
case Unknown
public var description: String {
switch self {
case .Offline: return "Offline"
case .Online(let type): return "Online (\(type))"
case .Unknown: return "Unknown"
}
}
}
public class Reachability {
func connectionStatus() -> ReachabilityStatus {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = (withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}) else {
return .Unknown
}
var flags : SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return .Unknown
}
return ReachabilityStatus(reachabilityFlags: flags)
}
func monitorReachabilityChanges() {
let host = "google.com"
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
let reachability = SCNetworkReachabilityCreateWithName(nil, host)!
SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in
let status = ReachabilityStatus(reachabilityFlags: flags)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil, userInfo: ["Status": status.description])}, &context)
SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)
}
}
extension ReachabilityStatus {
public init(reachabilityFlags flags: SCNetworkReachabilityFlags) {
let connectionRequired = flags.contains(.connectionRequired)
let isReachable = flags.contains(.reachable)
let isWWAN = flags.contains(.isWWAN)
if !connectionRequired && isReachable {
if isWWAN {
self = .Online(.WWAN)
} else {
self = .Online(.WiFi)
}
} else {
self = .Offline
}
}
}
答案 3 :(得分:6)
由于不推荐使用sendSynchronousRequest,我尝试了这个,但在响应完成之前调用了“返回状态”。
这个答案很有效,Check for internet connection with Swift
这是我尝试过的:
import Foundation
public class Reachability {
class func isConnectedToNetwork()->Bool{
var Status:Bool = false
let url = NSURL(string: "http://google.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
print("data \(data)")
print("response \(response)")
print("error \(error)")
if let httpResponse = response as? NSHTTPURLResponse {
print("httpResponse.statusCode \(httpResponse.statusCode)")
if httpResponse.statusCode == 200 {
Status = true
}
}
}).resume()
return Status
}
}
答案 4 :(得分:5)
SWIFT 3: 检查 wifi 和互联网连接:
import Foundation
import SystemConfiguration
public class Reachability {
public 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)
}
}
<强> USAGE:强>
if Reachability.isConnectedToNetwork() == true {
print("Connected to the internet")
// Do something
} else {
print("No internet connection")
// Do something
}
答案 5 :(得分:4)
您也可以使用以下答案。
func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void)
{
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: "http://www.google.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:
{(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
let rsp = response as NSHTTPURLResponse?
completionHandler(internet:rsp?.statusCode == 200)
})
}
func yourMethod()
{
self.checkInternet(false, completionHandler:
{(internet:Bool) -> Void in
if (internet)
{
// "Internet" mean Google
}
else
{
// No "Internet" no Google
}
})
}
答案 6 :(得分:1)
SWIFT 3:检查3G&amp; Wi-Fi连接
DispatchQueue.main.async {
let url = URL(string: "https://www.google.com")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) {data, response, error in
if error != nil {
// do something here...
print("Internet Connection not Available!")
}
else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
// do something here...
print("Internet Connection OK")
}
print("statusCode: \(httpResponse.statusCode)")
}
}
task.resume()
}
答案 7 :(得分:1)
对于Swift 5:
import Network
let monitor = NWPathMonitor()
func checkInterwebs() -> Bool {
var status = false
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
status = true // online
}
}
return status
}
答案 8 :(得分:1)
我找到了所有答案中最好的,并且每次都会不断检查Internet连接状态。
首先,为网络框架添加一个导入:
import Network
接下来,创建NWPathMonitor的实例
let monitor = NWPathMonitor()
要尝试一下,
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
print("We're connected!")
} else {
print("No connection.")
}
print(path.isExpensive)
}
请记住,每次连接状态更改时都会调用该闭包。
let queue = DispatchQueue(label: "Monitor")
monitor.start(queue: queue)
这是我在View控制器中使用它的方式,
class testViewController: UIViewController {
@IBOutlet weak var status: UILabel!
let monitor = NWPathMonitor()
override func viewDidLoad() {
super.viewDidLoad()
let queue = DispatchQueue(label: "Monitor")
monitor.start(queue: queue)
_ = NWPathMonitor(requiredInterfaceType: .cellular)
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
print("We're connected!")
DispatchQueue.main.async {
self.status.text = "We're connected!"
}
} else {
print("No connection.")
DispatchQueue.main.async {
self.status.text = "No connection."
}
}
}
}
答案 9 :(得分:0)
if isInternetAvailable()
{
print("if called Internet Connectivity success \(isInternetAvailable())");
}else{
print("else called Internet Connectivity success \(isInternetAvailable())");
}
func isInternetAvailable() -> 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)
}
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
// print(isReachable && !needsConnection)
return (isReachable && !needsConnection)
}
在Swift 4中工作
答案 10 :(得分:0)
如果您在项目中使用Alamofire,则可以使用以下示例函数:
import Alamofire
class Network {
func isConnected(_ complition: @escaping(Bool) -> Void) {
let retVal = NetworkReachabilityManager()!.isReachable
complition(retVal)
}
}