reachabilityWithAddress在Objective C编程中不起作用 [英] reachabilityWithAddress is not working in Objective C programming
问题描述
我想用ip检查服务器是否有效,例如, 74.125.71.104(Google的IP)
I want to check a server is live or not with ip, for example, 74.125.71.104 (Google's ip)
//分配一个可达性对象
// allocate a reachability object
`struct sockaddr_in address;
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
address.sin_port = htons(80);
address.sin_addr.s_addr = inet_addr("74.125.71.104");`
Reachability *reach = [Reachability reachabilityWithAddress:&address];
但那些不起作用。
我改为 reachabilityWithHostname
,它正在工作。
推荐答案
请导入 #include< arpa / inet.h>
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
struct sockaddr_in address;
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
address.sin_port = htons(8080);
address.sin_addr.s_addr = inet_addr("216.58.199.174"); //google ip
self.internetReachability = [Reachability reachabilityWithAddress:&address];
[self.internetReachability startNotifier];
[self updateInterfaceWithReachability:self.internetReachability];
编辑
根据您的评论,不会调用您的可访问性块。我总是使用通知,不太了解可达性块。所以我更喜欢使用以下通知。
As per your comments your reachability blocks are not called. I always use notifications not much aware of reachability blocks. So I prefer using notifications as follow.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
struct sockaddr_in address;
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
address.sin_port = htons(8080);
address.sin_addr.s_addr = inet_addr("216.58.199.174");
self.internetReachability = [Reachability reachabilityWithAddress:&address];
[self.internetReachability startNotifier];
[self updateInterfaceWithReachability:self.internetReachability];
现在,只要您的互联网状态发生变化,就会触发可更新性实例触发更改方法:)
Now whenever your internet status changes reachabilityChanged method will be triggerred with reachability instance :)
- (void) reachabilityChanged:(NSNotification *)note {
Reachability* curReach = [note object];
[self updateInterfaceWithReachability:curReach];
}
最后实现updateInterfaceWithReachability为
Finally implement updateInterfaceWithReachability as
- (void)updateInterfaceWithReachability:(Reachability *)reachability {
NetworkStatus netStatus = [reachability currentReachabilityStatus];
switch (netStatus)
{
case NotReachable: {
//not reachable
}
break;
case ReachableViaWWAN:
case ReachableViaWiFi: {
//reachable via either 3g or wifi
}
break;
}
}
希望这有帮助。
这篇关于reachabilityWithAddress在Objective C编程中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!