我想创建用于检查互联网连接的公共类,当互联网改变其状态时,它应该通知我。
我正在使用AFNetworking检查互联网状态。
这是我试过的代码,但它不起作用请帮助我犯错误的地方?
CheckInternet
是我从NSObject
CheckInternet.h
#import <Foundation/Foundation.h>
@interface CheckInternet : NSObject
+ (void)startNetworkMonitoring;
+ (BOOL)isInternetConnectionAvailable;
@end
CheckInternet.m
#import "CheckInternet.h"
#import "AFNetworking.h"
@implementation CheckInternet
+ (void)startNetworkMonitoring
{
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
// Check the reachability status and show an alert if the internet connection is not available
switch (status) {
case -1:
// AFNetworkReachabilityStatusUnknown = -1,
NSLog(@"The reachability status is Unknown");
break;
case 0:
// AFNetworkReachabilityStatusNotReachable = 0
NSLog(@"The reachability status is not reachable");
break;
case 1:
NSLog(@"The reachability status is reachable via wan");
[[NSNotificationCenter defaultCenter] postNotificationName:@"reachabilityChanged" object:nil];
break;
case 2:
// AFNetworkReachabilityStatusReachableViaWiFi = 2
NSLog(@"The reachability status is reachable via WiFi");
[[NSNotificationCenter defaultCenter] postNotificationName:@"reachabilityChanged" object:nil];
break;
default:
break;
}
}];
}
#pragma mark - Check Internet Network Status
+ (BOOL)isInternetConnectionAvailable {
return [AFNetworkReachabilityManager sharedManager].reachable;
}
@end
在我的ViewController.m
(此处我想检查互联网状态)
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[CheckInternet startNetworkMonitoring];
if ([CheckInternet isInternetConnectionAvailable])
{
NSLog(@"---- Internet YES------ ");
}
else
{
NSLog(@"----- Internet NO------ ");
}
}
//This is not called...
- (void)reachabilityChanged:(NSNotification *)notification
{
NSLog(@"---- reachabilityChanged ----");
}
提前感谢您!
答案 0 :(得分:1)
首先,我建议您开始在AppDelegate
中监控您的网络活动。将[CheckInternet startNetworkMonitoring];
移至didFinishLaunchingWithOptions
其次,将以下行添加到case == 0
:
[[NSNotificationCenter defaultCenter] postNotificationName:@"reachabilityChanged" object:[NSNumber numberWithInteger:one]];
另外请确保您使用通知发布连接状态。因为它是一个整数,所以需要将它包装在一个对象中(通常包含在NSNumber中)。
第三,您需要遵守reachabilityChanged
通知。
在viewDidLoad
。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:@"reachabilityChanged"
object:nil];
在你的函数- (void)reachabilityChanged:(NSNotification *)notification
中,你应该能够访问通知的userInfo属性并读取那里的状态代码。
此外,一旦viewController消失,请不要忘记取消观察通知。所以在dealloc
[NSNotificationCenter defaultCenter] removeObserver:self];