头文件(头文件中用到了单例模式的宏定义)
//
// OpenHABWiFi.h
// openHAB
//
// Created by XMYY-19 on 2018/1/18.
// Copyright © 2018年 openHAB e.V. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Singleton.h"
/**
WiFi相关的功能
*/
@interface OpenHABWiFi : NSObject
// 单例模式
singleton_interface(OpenHABWiFi)
/**
开始监听WiFi的变化
*/
- (void)starListeningWiFiChange;
/**
停止监听WiFi的变化
*/
- (void)stopListeningWiFiChange;
@end
.m文件
//
// OpenHABWiFi.m
// openHAB
//
// Created by XMYY-19 on 2018/1/18.
// Copyright © 2018年 openHAB e.V. All rights reserved.
//
#import "OpenHABWiFi.h"
#import "Reachability.h"
#import "OpenHABSSDPService.h"
@interface OpenHABWiFi()
// 监听WiFi变化相关的类
@property (nonatomic, strong) Reachability *hostReachability;
@end
@implementation OpenHABWiFi
singleton_implementation(OpenHABWiFi)
// 单例模式模式初始化内容
-(instancetype)init
{
if (self = [super init]) {
}
return self;
}
- (void)starListeningWiFiChange{
//1.监听WiFi之间的切换
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),NULL,onNotifyCallback,CFSTR("com.apple.system.config.network_change"),NULL,CFNotificationSuspensionBehaviorDeliverImmediately);
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
//2.监听WiFi与4G等其他网络之间的切换
NSString *remoteHostName = @"www.apple.com";
self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
[self.hostReachability startNotifier];
[self updateInterfaceWithReachability:self.hostReachability];
}
static void onNotifyCallback(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
NSString* notifyName = (__bridge NSString *)name;//(NSString*)name;
// WiFi之间的切换
if ([notifyName isEqualToString:@"com.apple.system.config.network_change"]) {
NSLog(@"i am listening networkChange:%@",notifyName);
} else {
NSLog(@"intercepted %@", notifyName);
}
}
- (void) reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
[self updateInterfaceWithReachability:curReach];
}
-(void)updateInterfaceWithReachability:(Reachability *)reachability
{
if (reachability == self.hostReachability)
{
NetworkStatus netStatus = [reachability currentReachabilityStatus];
switch (netStatus)
{
case NotReachable:
{
NSLog(@"《NotReachable》");
break;
}
case ReachableViaWWAN:
{
NSLog(@"《ReachableViaWWAN》");
break;
}
case ReachableViaWiFi:
{
NSLog(@"《ReachableViaWiFi》");
break;
}
}
}
}
// 移除通知
- (void)stopListeningWiFiChange
{
}
- (void)startSSDP
{
NSLog(@"《StartSSDP》");
}
@end