頭文件(頭文件中用到了單例模式的宏定義)
//
// 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相關(guān)的功能
*/
@interface OpenHABWiFi : NSObject
// 單例模式
singleton_interface(OpenHABWiFi)
/**
開始監(jiān)聽WiFi的變化
*/
- (void)starListeningWiFiChange;
/**
停止監(jiān)聽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()
// 監(jiān)聽WiFi變化相關(guān)的類
@property (nonatomic, strong) Reachability *hostReachability;
@end
@implementation OpenHABWiFi
singleton_implementation(OpenHABWiFi)
// 單例模式模式初始化內(nèi)容
-(instancetype)init
{
if (self = [super init]) {
}
return self;
}
- (void)starListeningWiFiChange{
//1.監(jiān)聽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.監(jiān)聽WiFi與4G等其他網(wǎng)絡(luò)之間的切換
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