- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在开发一个复杂的应用程序,我想在每个从服务器接收数据的 ViewController 上测试两个主机的互联网可达性我目前正在使用这个库来实现可达性
我想创建一个简单的方法或扩展来检查互联网和主机的可达性我已经使用了下面库中的示例代码:`import UIKit
import Reachability
class VC22: UIViewController {
@IBOutlet weak var networkStatus: UILabel!
@IBOutlet weak var hostNameLabel: UILabel!
var reachability: Reachability?
override func viewDidLoad() {
super.viewDidLoad()
// Start reachability without a hostname intially
setupReachability(nil, useClosures: true)
startNotifier()
// After 5 seconds, stop and re-start reachability, this time using a hostname
let dispatchTime = DispatchTime.now() + DispatchTimeInterval.seconds(5)
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
self.stopNotifier()
self.setupReachability("http://81.28.42.42:4242/", useClosures: true)
self.startNotifier()
let dispatchTime = DispatchTime.now() + DispatchTimeInterval.seconds(5)
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
self.stopNotifier()
self.setupReachability("invalidhost", useClosures: true)
self.startNotifier() }
}
}
func setupReachability(_ hostName: String?, useClosures: Bool) {
hostNameLabel.text = hostName != nil ? hostName : "No host name"
print("--- set up with host name: \(hostNameLabel.text!)")
let reachability = hostName == nil ? Reachability() : Reachability(hostname: hostName!)
self.reachability = reachability
if useClosures {
reachability?.whenReachable = { reachability in
DispatchQueue.main.async {
self.updateLabelColourWhenReachable(reachability)
}
}
reachability?.whenUnreachable = { reachability in
DispatchQueue.main.async {
self.updateLabelColourWhenNotReachable(reachability)
}
}
} else {
NotificationCenter.default.addObserver(self, selector: #selector(VC22.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability)
}
}
func startNotifier() {
print("--- start notifier")
do {
try reachability?.startNotifier()
} catch {
networkStatus.textColor = .red
networkStatus.text = "Unable to start\nnotifier"
return
}
}
func stopNotifier() {
print("--- stop notifier")
reachability?.stopNotifier()
NotificationCenter.default.removeObserver(self, name: ReachabilityChangedNotification, object: nil)
reachability = nil
}
func updateLabelColourWhenReachable(_ reachability: Reachability) {
print("\(reachability.description) - \(reachability.currentReachabilityString)")
if reachability.isReachableViaWiFi {
self.networkStatus.textColor = .green
} else {
self.networkStatus.textColor = .blue
}
self.networkStatus.text = reachability.currentReachabilityString
}
func updateLabelColourWhenNotReachable(_ reachability: Reachability) {
print("\(reachability.description) - \(reachability.currentReachabilityString)")
self.networkStatus.textColor = .red
self.networkStatus.text = reachability.currentReachabilityString
}
func reachabilityChanged(_ note: Notification) {
let reachability = note.object as! Reachability
if reachability.isReachable {
updateLabelColourWhenReachable(reachability)
} else {
updateLabelColourWhenNotReachable(reachability)
}
}
deinit {
stopNotifier()
}
}
这工作正常,但我只需要一个 bool 值来告诉我它是否已连接,可以通过应用程序重复使用
更新 目前我正在使用以下类(class):
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(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 = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = flags == .reachable
let needsConnection = flags == .connectionRequired
return isReachable && !needsConnection
}
}
并像下面这样在 viewControllers 中使用:
if Reachability.isConnectedToNetwork() == true {
print("Internet connection OK")
JSONParseFunction()
} else {
print("Internet connection FAILED")
let alert = UIAlertView(title: "You are not connect to internet", message: "please check you connectivity", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
这样我只检查互联网我需要检查主机和互联网
最佳答案
有没有理由不把它放在你的 AppDelegate
中并在那里订阅观察者,而不是在特定的 vc 上这样做?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
prepareReachabilityObserver()
return true
}
private func prepareReachabilityObserver() {
AppDelegate.reachability.whenUnreachable = { reachability in
DispatchQueue.main.async {
print("Not reachable")
}
}
do {
try AppDelegate.reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
在 host verification extension
部分,我可能会使用类似的东西:
extension UIViewController {
internal func isReachable() -> Bool {
//this is the function you already have.
}
}
然后你可以在每个 View Controller 中使用它
self.isReachable() //'self' is a UIViewController in this case.
除此之外,我无法理解您的问题,因为您似乎已经解决了这个问题。
编辑:我想我现在明白你的问题了。您要检查是否您可以访问,以及您传递的主机名是否也可以访问。我不认为同时处理这两个问题是最好的主意,因为一个是可达性问题(“我可以得到传出连接吗?”)另一个是连接问题(“我可以从这个偏远的地方?”或“此请求是否超时?”)。
我目前处理它的方式是 AppDelegate 之类的可达性,然后以逐个请求的方式处理超时(然后您可以在网络范围内进行概括)。更加具体:AppDelegate
设置可达性。然后我有一个 RequestsManager
,它使用配置的 timeout
处理服务调用。
然后你可以这样做:
RequestManager.makeRequest("https://an.endpoint.of.yours",
onSuccess: {},
onFailure: { //Here goes your timeout behaviour.
})
我在哪里传递主机名?老实说,我认为这是一种不必要的行为。您不会尝试打开门
然后您打开门
。你只是尝试看看你是否成功。这里也一样。您尝试发出请求,是否成功?惊人的。不是吗?相应处理。如果失败是因为端点已关闭,或者是因为您没有可用的数据计划或网络已关闭,您(应用程序)会在意什么?无论哪种方式,请求都会超时,这就是您所关心的。
同样,这一切都是假设我真的理解你,我不是 100% 确定。
关于ios - 为可达性(主机/互联网 WIFI、蜂窝)创建一个易于使用的扩展/功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43745810/
我想检查 wifi 是否有互联网连接。大多数解决方案/方法(包括 alamofire)仅在设备仅连接到 wifi 时才返回 true,不检查 wifi 是否有互联网连接。 最佳答案 苹果的reacha
是否可以通过 wifi 网络发送一些弹出消息或短信/彩信?如果是如何发送。 我的用例是向连接到我的开放 wifi 网络的设备发送某种弹出窗口。弹出窗口可以是图形广告或任何信息之类的东西。 任何人都可以
假设您对无线路由器有完全的编程控制(运行 OpenWrt 或 DD-WRT - Linux)。路由器配置为广播 ssid,并且网络完全开放。 移动用户(iPhone/Android/BB)走过来。 1
我正在编写一个 Android 应用程序,并试图弄清楚是否有可靠的方法来确定手机何时连接到特定的 wifi 网络。 例如,我只想在连接到家庭 wifi 时执行某些操作。 有人知道这是否可行吗? 最佳答
我想把我的 Raspberry PI 3 变成类似 WiFi 信号放大器、无线中继器/扩展器或 WiFi 热点之类的东西,可以放大微弱的 WiFi 信号。 经过一番研究,我找到了这个教程,点击 her
我目前正在使用我的 mongodb 服务器以及正在运行的 Nodejs 服务器测试我的 Android 应用程序。我希望服务器可以像内联网一样通过 WiFi 访问,以便手机上的应用程序可以访问本地服务
问题陈述 调用pcap_activate()结果 PCAP_ERR_RFMON_NOTSUP错误,即不支持射频监控模式。 上下文 我正在编写小型 C 程序,其工作是在监听模式下监听笔记本电脑的 wif
想象一下这种情况,周围有一些智能手机和计算机,它们的 WiFi 适配器(无线适配器)打开,但没有必要连接到网络。 有没有办法通过 Linux 机器查看 MAC 地址? 任何见解表示赞赏。 最佳答案 断
我在 WiFi 连接检测方面遇到问题。我的目标是检测用户何时在不同的 WiFi 之间切换。我发现this ,但它只检测 WiFi 何时建立。就我而言,我需要知道手机上的一个 WiFi 网络何时更改为另
我想获取一些有关 Wifi 的信息,例如 SSID 名称、IP 地址和速度,所以我编写了这段代码 WifiManager wifiMgr = (WifiManager) getSystemServic
我正在安装一个系统来监控一些传感器,并根据它们打开/关闭几盏灯。 为了进一步的数据分析,我们还想将该数据发送到中央服务器,因此我们添加了 Wifi 屏蔽。 请记住,如果没有网络,系统应该可以正常运行。
这两天我一直在苦苦挣扎,我找不到解决办法。我尝试了这段代码,但随着时间的推移,它在 Android 5(Lollipop) 上运行,但在 7.1.1.(Nougat) 上不起作用。我有另一个场景,手机
我正在开发一些软件来管理通过 ZigBee 与 Remote 通信的设备。我们希望设备能够通过 Wi-Fi 与网络服务器和/或智能手机通信,以便我们的软件可以与之交互。 ZigBee Remote 很
自 setWifiEnabled在 Android 10 上已弃用,如何在 Android 10 设备上以编程方式启用 wifi? 是否无法在 Android 10+ (SDK 29) 上以编程方式启
我正在尝试从 WiFi 数据包中获取 RSSI 或信号强度。 我还想要来自“WiFi 探测请求”的 RSSI(当有人在搜索 WiFi 热点时)。 我设法从 kismet 日志中看到它,但这只是为了确保
关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。 此问题是由拼写错误或无法再重现的问题引起的。虽然类似的问题可能是 on-topic
我需要一个 IOS 应用程序,用户将在其中启动应用程序,录制音频语音(通过设备麦克风),该语音语音将广播给同一网络上的其他用户,所有这些都必须通过无线连接(WIFI)进行直播。 我对可能的解决方案进行
更新: 我指出了问题的来源。为了避免任何复杂化,我使用 ScanNetwork 示例,所以我什至不必输入 SSID .该代码在遇到 WiFi.status() 后立即停止在板上运行. 我有一个 Ser
在我的 android 应用程序中,我连接到 WiFi 网络。但是,例如,如果我多次连接到这个网络,这个网络的名称就会多次出现在标准的 android WiFi 列表中。我怎样才能避免这种情况? 我的
我有可用的 wifi 网络列表列表,现在我想连接到特定网络。所以请指导我在 ListView 中获取网络列表后必须做什么。 **package com.example.wifilist imp
我是一名优秀的程序员,十分优秀!