我正在构建一个应用程序并尝试检查并查看网络上是否仍有设备(通过连接到设备IPAddress)。我正在使用可达性来确认它是否可用。
当我为iOS设备进行网络访问(例如打开飞行模式)时,一切正常,但如果我从网络中删除设备,则可访问性似乎没有注意到更改。
似乎可达性是缓存结果,而不是看到更新。
答案 0 :(得分:2)
不要使用可达性!
使用这段代码来代替它;
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
wait(25000);
if (connected == NULL) {
NSLog(@"Not Connected");
//Code to show if not connected
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Oops! You aren't connected to the Internet."
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
} else {
NSLog(@"Connected Successfully!");
//Any other code for successful connection
}
答案 1 :(得分:2)
SCReachability
API仅检查本地硬件是否配置为可以到达指定的地址;它实际上并没有试图达到它。要确定目标是否还活着,您必须尝试打开它的连接。
答案 2 :(得分:1)
结帐this answer。虽然像素比特的答案是可行的,但是burtlo提出的只是等待25秒并不是一个好主意。使用NSURLConnection更加清晰。
答案 3 :(得分:0)
Apple更新了Reachabilty类文件。您可以使用最新的Xcode进行测试。 这里是链接: Apple Reachabilty Sample Code
我在iPhone 6版本10.3.1上使用Xcode 8.3.1进行了测试。 它将通知用户网络状态的变化。