检查swift中的互联网连接是否可用 [英] Check if internet connection availabile in swift
问题描述
是否有Apple框架捆绑包可以检测是否存在互联网连接?目前我的应用程序在尝试在没有互联网连接的情况下对用户的位置进行地理定位时崩溃。
Is there an Apple framework bundle to detect if there's an internet connection? Currently my application crashes when it tries to geolocate the user's position without an internet connection.
/*inside locationManager didUpdateLocations method*/
var currentLocation:CLLocation? = locations[0] as? CLLocation
geocoder = CLGeocoder()
//Crashes on line below when there isn't an internet connection
//Need to add function to check if internet connection is live
//Before running reverseGeocodeLocation
geocoder.reverseGeocodeLocation (currentLocation,handleGeocode)
我有点swift和ios编程的新手 - 我的道歉。
I'm a bit new to swift and ios programming - my apologies.
推荐答案
不是一个成熟的网络检查库,但我发现这是一种检查网络可用性的简单方法。我设法将它翻译成Swift,这里是最终代码。
Not a full-fledged network checking library but I found this simple method for checking the network availability. I managed to translate it to Swift and here the final code.
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) ? true : false
}
}
它适用于两者3G和WiFi连接。我还通过一个工作示例将其上传到我的 Github 。如果您正在寻找一种纯粹在Swift中检查网络可用性的简单方法,您可以使用它。
It works for both 3G and WiFi connections. I've also uploaded it to my Github with a working example. If you're looking for a simple way to check for network availability purely in Swift, you can use it.
这篇关于检查swift中的互联网连接是否可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!