一般仅Wi-Fi下载都是一个switch控制,我们需要根据switch的on属性和当前网络状态来判定。
我们通过一个单例类来创造一个全局属性,这里我们使用AFNetworking给我们提供的网络监控方法
@interface allowNet : NSObject
@property (nonatomic) BOOL allow;
@property (nonatomic) AFNetworkReachabilityStatus netState;
+ (instancetype)shareInstance;
@end
@implementation allowNet
static allowNet *net;
+ (instancetype)shareInstance{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
net = [[self alloc]init];
});
return net;
}
@end
//在AppDelegate 的didFinish。。。方法里面设置网络监听
// 1.创建网络监听者管理者对象
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
// 2.设置监听
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
[allowNet shareInstance].netState = status;
}];
// 3.开始监听
[manager startMonitoring];
//设置监听后应该在马上初始化单例的allow属性
//这里通过userDefaults的方法把switch的on属性保存下来并获取,保存方法不在赘述
BOOL sw = [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"];
if (sw && [allowNet shareInstance].netState == AFNetworkReachabilityStatusReachableViaWiFi) {
[allowNet shareInstance].allow = YES;
}else if(!sw){
[allowNet shareInstance].allow = YES;
}else{
[allowNet shareInstance].allow = NO;
}
//到这里已经实现了最基本的操作,然后给switch addTarget:self action:@selector(wifiSwChange:) forControlEvents:(UIControlEventValueChanged)
- (void)wifiSwChange:(UISwitch *)sender{
//持久化保存开关状态
[[NSUserDefaults standardUserDefaults] setObject:@(sender.on) forKey:@"switch"];
//根据开关设置网络允许
if (sender.on && [allowNet shareInstance].netState == AFNetworkReachabilityStatusReachableViaWiFi) {
[allowNet shareInstance].allow = YES;
}else if(!sender.on){
[allowNet shareInstance].allow = YES;
}else{
[allowNet shareInstance].allow = NO;
}
//判断是否有正在下载的任务,这里根据实际情况进行判断,因为有可能正在执行下载任务的时候选择了此按钮,应该及时告知用户
if ([DLTableViewController shareInstance].loadingArr.count != 0 && sender.on) {//loadingArr存放的就是下载任务,所以根据这个来判断
//提示用户是否确定要关闭下载
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"当前有任务正在下载" message:@"确定要开启吗?" preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//发送暂停下载的通知,下载类收到通知,执行暂停操作即可。
[[NSNotificationCenter defaultCenter] postNotificationName:@"pauseDownload" object:nil userInfo:nil];
}];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
sender.on = !sender.on;
}];
[alert addAction:action1];
[alert addAction:action2];
[self presentViewController:alert animated:YES completion:nil];
}
}