gpt4 book ai didi

ios - 在 iOS 中使用 AFNetworking 2 检查连接的最佳方法?

转载 作者:行者123 更新时间:2023-11-29 12:16:27 44 4
gpt4 key购买 nike

我想在向服务器发出请求之前检查用户设备是否连接到互联网。为此,我在 AppDelegate 类中执行此操作

- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
[self connectivity];
}
-(void)connectivity
{
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){

}];

// Set the reachabilityManager to actively wait for these events
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

当我提出任何要求时我都会这样做

AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
BOOL con = (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN);
//BOOL con =[AFNetworkReachabilityManager sharedManager].reachable;//give same result as networkReachabilityStatus

但是当我第一次提出请求时,它给了我NO,一段时间后它给出了正确的值。请建议监控连接的最佳方法。

最佳答案

您可以检查属性networkReachabilityStatus:

AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
BOOL rechable = (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN);

如果您想在statusAFNetworkReachabilityStatusUnknown 时尝试执行 smth,您可以使用:

BOOL rechable = (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusUnknown);

附言

可达性检查是异步操作,参见SCNetworkReachabilityRef ,因此您无法在 applicationDidFinishLaunching 方法中获取 networkReachabilityStatus。

关于ios - 在 iOS 中使用 AFNetworking 2 检查连接的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31874747/

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