gpt4 book ai didi

ios - reachabilityWithAddress 在 Objective C 编程中不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:54 27 4
gpt4 key购买 nike

我想通过 ip 检查服务器是否处于事件状态,例如,74.125.71.104(Google 的 ip)

//分配可达性对象

`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];

编辑

根据您的评论,您的可达性 block 没有被调用。我总是使用不太了解可达性 block 的通知。所以我更喜欢如下使用通知。

[[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];

现在,只要您的互联网状态发生变化,reachabilityChanged 方法就会被 reachability 实例触发:)

- (void) reachabilityChanged:(NSNotification *)note {
Reachability* curReach = [note object];
[self updateInterfaceWithReachability:curReach];
}

最后实现 updateInterfaceWithReachability 为

- (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;
}
}

希望这对您有所帮助。

关于ios - reachabilityWithAddress 在 Objective C 编程中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37742367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com