我使用“pod install”安装AFNetworking 2.0,并使用App.xcworkspace。 使用AFNetworking 2.0我成功发送了POST请求,但是由于可达性,我遇到了问题。 我需要监视套接字何时打开和关闭,我的代码不起作用,我忘记了什么?
// Check server socket available
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_len = sizeof(serverAddr);
serverAddr.sin_port = htons(80);
serverAddr.sin_addr.s_addr = inet_addr("192.168.1.108");
AFNetworkReachabilityManager *reachability = [AFNetworkReachabilityManager managerForAddress:&serverAddr];
[reachability setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"No Internet Connection");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"WIFI");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"3G");
break;
default:
NSLog(@"Unknown network status");
break;
}
}];
[reachability startMonitoring];
答案 0 :(得分:1)
我想我发现了这个问题。看起来AFNetworking的回调机制不能正常工作 - 查看AFNetworkReachabilityManager的startMonitoring
方法:有一个:
if (strongSelf.networkReachabilityStatusBlock) {...
无论你是否设置了回调,它似乎都会失败。
要解决此问题,我已将以下方法添加到AFNetworkReachabilityManager:
- (void)startMonitoringWithStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block
{
[self stopMonitoring];
if (!self.networkReachability) {
return;
}
__weak __typeof(self)weakSelf = self;
AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
strongSelf.networkReachabilityStatus = status;
if (block) {
block(status);
}
};
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityGetFlags(self.networkReachability, &flags);
dispatch_async(dispatch_get_main_queue(), ^{
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
callback(status);
});
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
}
这基本上做同样的事情,但引用了方法参数中的块而不是来自可达性管理器的属性。