【发布时间】:2016-03-18 10:23:42
【问题描述】:
我有一个应用程序,它是完整的地图视图。我需要的是,如果用户没有连接到互联网,我需要显示一些警报。我已经做到了。这是代码:
Reachability.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(kCFAllocatorDefault, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = flags == .Reachable
let needsConnection = flags == .ConnectionRequired
return isReachable && !needsConnection
}
}
if Reachability.isConnectedToNetwork() == true {
println("Internet connection OK")
} else {
println("Internet connection FAILED")
var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
但我需要的是:当用户未连接到互联网时,会显示一条UIAlertView 消息。在那个警报中,我有一个OK 按钮。因此,在用户连接到互联网之前,可以将他们重定向到移动数据开/关设置,或者可以显示UIAlertView 消息直到用户连接到互联网..
请帮帮我!!
【问题讨论】:
-
如果我是您的应用程序的用户,我不会在意应用程序启动时是否已连接——除非我需要访问远程服务。因此,在您的应用程序中,只需尝试连接何时请求它,当由于无法访问服务器而失败时,让用户知道。
标签: ios swift reachability