网络监听
wifi、2g、3g、4g、无网
集成Reachability + CTTelephonyNetworkInfo的步骤
- 下载
Reachability.h
、Reachability.m
,并导入项目中 - 添加
CoreTelephony.framework
(Targets → Build Phases → Link Binary With Libraries
) - 导入头文件
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
- (Reachability *)reachability{
if (!_reachability) {
_reachability = [Reachability reachabilityForInternetConnection];
}
return _reachability;
}
//启动网络监听
- (void*)startNetStateObserve {
// 监听网络状态改变的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
[self.reachability startNotifier];
}
-(void)networkStateChange {
NSString * networkType = [self getCurrentNetworkType];
NSLog(@"%@",networkType);
container::NetworkStatusUtilsIOS::getNetworkStatusUtilsIOSInstance()->ChangeNetwork([networkType UTF8String]);
}
/*
* 判断当前网络类型
*/
-(NSString *)getCurrentNetworkType {
//Reachability * reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
NetworkStatus netStatus = [self.reachability currentReachabilityStatus];
NSString * networkType = @"";
switch (netStatus) {
case ReachableViaWiFi:
networkType = @"WIFI";
break;
case ReachableViaWWAN: {
networkType = @"4G/3G";
// 判断蜂窝移动类型
CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
if (@available(iOS 12.0,*)) {
NSDictionary<NSString *, NSString *> *infoDic = networkInfo.serviceCurrentRadioAccessTechnology;
NSLog(@"infoDic = %@", infoDic);
} else {
if ([networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyWCDMA]) {
networkType = @"2G";
}
else if ([networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSDPA] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSUPA] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMA1x] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD]) {
networkType = @"3G";
}
else if ([networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
networkType = @"4G";
}
}
}
break;
case NotReachable:\
networkType = @"当前无网络连接";\
break;
}
return networkType;
}
截屏
//监听
- (void)registNotification{
[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(getScreenshot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}
- (void)getScreenshot:(NSNotification *)notification{
NSLog(@"捕捉截屏事件");
UIImage *shortImg = [UIImage imageWithData:[self imageDataScreenShot]];
NSString * shortImgStr = [[NSString alloc]initWithData:[self imageDataScreenShot] encoding:4];
if ([shortImgStr length]) {
container::CaptureScreenIOS::getCaptureScreenIOSInstance()->UserCaptureScreen([shortImgStr UTF8String]);
}
}
//当前屏幕图片data
- (NSData *)imageDataScreenShot{
CGSize imageSize = CGSizeZero;
imageSize = [UIScreen mainScreen].bounds.size;
UIGraphicsBeginImageContextWithOptions(imageSize, **NO**, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
for (UIWindow window in [[UIApplication sharedApplication] windows]){
CGContextSaveGState(context);
CGContextTranslateCTM(context, window.center.x, window.center.y);
CGContextConcatCTM(context, window.transform);
CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
if ([window respondsToSelector: @selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
[window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
}
else{
[window.layer renderInContext:context];
}
CGContextRestoreGState(context);
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return UIImagePNGRepresentation(image);
}
录音
#import "JAudioRecord.h"
#import <AVFoundation/AVFoundation.h>
@interface JAudioRecord()<AVAudioRecorderDelegate>
/** 录音对象*/
@property(nonatomic ,strong) AVAudioRecorder *recorder;
@end
@implementation JAudioRecord
+ (instancetype)sharedSingleton {
static BMAudioRecord *_sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedSingleton = [[self alloc] init];
});
return _sharedSingleton;
}
//获取当前时间戳 (以毫秒为单位),以当前时间作为 音频文件名
+(NSString *)getNowTimeTimestamp{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
[formatter setTimeZone:timeZone];
NSDate *datenow = [NSDate date];
NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
return timeSp;
}
//文件存储路径,音频文件类型 .aac
- (NSString*)getFilePath {
NSString * recordPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString * filePath = [recordPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.aac",[BMAudioRecord getNowTimeTimestamp]]];
return filePath;
}
//获取音频文件 录音时长
- (double)getFlieDuration {
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.recorder.url options:nil];
CMTime time = asset.duration;
double durationInSeconds = CMTimeGetSeconds(time);
return durationInSeconds;
}
- (AVAudioRecorder *)recorder
{
if (_recorder == nil) {
NSString *filePath = [self getFilePath];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSDictionary * dict = @{
AVFormatIDKey:@(kAudioFormatMPEG4AAC),
AVEncoderAudioQualityKey:@(AVAudioQualityMedium),//音频质量,采样质量
AVLinearPCMBitDepthKey:@(16),//通道
AVSampleRateKey:@(8000),// 采样率
AVNumberOfChannelsKey:@(2),// 通道数
AVLinearPCMIsFloatKey:@(YES)//比特 采样率
};
_recorder = [[AVAudioRecorder alloc]initWithURL:url settings:dict error:nil];
_recorder.delegate = self;
[_recorder prepareToRecord];
}
return _recorder;;
}
- (void)beginRecordWithMaxTime:(int)maxTime
{
NSLog(@"开始录音");
// 录音
NSString * apFilePath = @"";
NSError *error;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
if (!error) {
[self.recorder recordAtTime:self.recorder.deviceCurrentTime forDuration:maxTime];
}else {
NSLog(@"无法录音");
}
/*
[self.recorder recordForDuration:3]; // 从当前执行这行代码开始录音, 录音5秒
[recorder recordAtTime:recorder.deviceCurrentTime + 2]; // 2s, 需要手动停止
[self.recorder recordAtTime:self.recorder.deviceCurrentTime + 2 forDuration:3]; // 2s 3s
*/
}
- (void)pauseRecord {
NSLog(@"暂停录音");
if (self.recorder.isRecording) {
[self.recorder pause];
}
}
- (void)stopRecord {
NSLog(@"停止录音");
if (self.recorder.isRecording) {
[self.recorder stop];
}
}
#pragma mark --- AVAudioRecorderDelegate
/* audioRecorderDidFinishRecording:successfully: is called when a recording has been finished or stopped. This method is NOT called if the recorder is stopped due to an interruption. */
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag;{
NSLog(@"录音:%d",flag);
//录音文件 时长,可以做相应业务处理。
int totalTime = [self getFlieDuration];
}
/* if an error occurs while encoding it will be reported to the delegate. */
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error;{
NSLog(@"录音:%@",error);
}
- (void)getAuth{
__block BOOL bCanRecord = NO;
int flag = [self getMarcophonePermission];
if (flag != 2) {
NSLog(@"麦克风未授权");
[[AVAudioSession sharedInstance] performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
bCanRecord = granted;
}];
}else{
NSLog(@"麦克风已授权");
}
}
- (int)getMarcophonePermission{
int flag = -1;
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
switch (authStatus) {
case AVAuthorizationStatusNotDetermined:
//没有询问是否开启麦克风
flag = 1;
break;
case AVAuthorizationStatusRestricted:
//未授权,家长限制
flag = 0;
break;
case AVAuthorizationStatusDenied:
//玩家未授权
flag = 0;
break;
case AVAuthorizationStatusAuthorized:
//玩家授权
flag = 2;
break;
default:
break;
}
return flag;
}
@end