iOS-网络相关
2016-09-23 本文已影响0人
Mn_Su
第一.HTTP相关
第二.网络开发
第三.Swift版后台开发
=================获取网络信号======================
第一.Reachability 方法
_1.导入 Reachability.h 和 Reachability.m 文件 (自行下载)_
_2.相关控制器导入头文件和库文件 SystemConfiguration.framework_
_3.创建相关属性:_
@property (nonatomic, strong) Reachability *reachability;
_4.相关申明:_
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
self.reachability = [Reachability reachabilityWithHostname:@"www.baidu.com"];
[self.reachability startNotifier];
_5.相关方法:_
_5.相关方法:_
#pragma mark - 私有方法
// 实时监听网络状态
- (void)reachabilityChanged:(NSNotification *)notification
{
Reachability* curReach = [notification object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
[self updateInterfaceWithReachability:curReach];
}
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
if (reachability == _reachability)
{
NetworkStatus netStatus = [reachability currentReachabilityStatus];
switch (netStatus)
{
case NotReachable: {
NSLog(@"没有网络!");
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"友情提醒" message:@"暂无网络!请检查网络!" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[SVProgressHUD showWithStatus:@"数据恢复中!"];
}]];
[self presentViewController:alert animated:true completion:nil];
break;
}
case ReachableViaWWAN: {
NSLog(@"4G/3G");
[self loadingWeb];
[SVProgressHUD dismiss];
break;
}
case ReachableViaWiFi: {
NSLog(@"WiFi");
[self loadingWeb];
[SVProgressHUD dismiss];
break;
}
}
}
}
第二.从状态栏中获取网络类型,(弊端:手机无sim卡时,无法读取):
- (NSString *)getNetWorkStates{
UIApplication *app = [UIApplication sharedApplication];
NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
NSString *state = [[NSString alloc]init];
int netType = 0;
//获取到网络返回码
for (id child in children) {
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
//获取到状态栏
netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
switch (netType) {
case 0:
state = @"无网络";
//无网模式
break;
case 1:
state = @"2G";
break;
case 2:
state = @"3G";
break;
case 3:
state = @"4G";
break;
case 5:
{
state = @"wifi";
break;
default:
break;
}
}
}
//根据状态选择
}
return state;
}