是否有Apple框架捆绑包来检测是否存在互联网连接?当前,当我的应用程序尝试在没有互联网连接的情况下对用户的位置进行地理位置定位时会崩溃。
/*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编程有些陌生-抱歉。
这不是一个完善的网络检查库,但是我发现了这种简单的方法来检查网络可用性。我设法将其翻译为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) ? true : false } }
它适用于3G和WiFi连接。我还通过一个工作示例将其上传到了我的Github。如果您正在寻找一种简单的方法来纯粹在Swift中检查网络可用性,则可以使用它。