ios - 如果网络关闭并且输出控制台返回错误,则不会加载MapView

标签 ios swift error-handling mkmapview runtime-error

我需要你的支持。
我的应用程序使用MKMapView来显示 map 。我在模拟器和iPhone上对其进行了测试,但是当网络打开时,它可以正常运行;当网络关闭时,它不会加载,并且输出控制台返回以下错误:

 Could not determine current country code: Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x7f800e0e7520 {NSUnderlyingError=0x7f800e0207c0 "The Internet connection appears to be offline.", NSErrorFailingURLStringKey=http://gsp1.apple.com/pep/gcc, NSErrorFailingURLKey=http://gsp1.apple.com/pep/gcc, _kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, NSLocalizedDescription=The Internet connection appears to be offline.}

这些错误是否正常?还是必须处理?我不知道如何解决这些错误,以及在哪个 map View 的功能中检查网络连接。

谢谢,抱歉我的英语不好

最佳答案

您应该先检查是否已连接到网络-否则,您将无法使用 map 。

尝试这样的事情:

func hasConnection() -> 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
}

如果它为假,则应禁用该 map 。

关于ios - 如果网络关闭并且输出控制台返回错误,则不会加载MapView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29367374/

相关文章:

string - Swift - 可选字符串与隐式解包可选字符串

java - 实例化Java if语句引用错误

c - 不断收到错误 : "redefinition of typedef ' MYSTRUCT '"and "previous declaration of 'MYSTRUCT' was here"

ios - [SearchStockCell 保留] : message sent to deallocated instance

ios - 如何在重置之前向日志添加值(Swift 中的 CoreData)

php - 访问包括应用程序文件夹中的文件夹。

iphone - 仅使用 Core Graphics 和 CADisplayLink 的图像动画示例

ios - 什么时候不在 IOS 应用程序中使用 APNS?

ios - SwiftyJson 是否能够将自定义 swift 类转换为 json 字符串?

ios - NSObject 如何知道它是在哪个 View 中绘制的