苹果官方提供Demo
Demo地址下载
工具类
.h文件
#import <Foundation/Foundation.h>
@interface ZLUSBPlugInTool : NSObject
/**
* 判断是否连接成功(插上配件则为服务端)
*
* @return 返回连接状态
*/
+ (BOOL)isConnectSuccess;
@end
.m文件
#import "ZLUSBPlugInTool.h"
#import <ExternalAccessory/ExternalAccessory.h>
static NSMutableArray *_accessoryList; // 连接配件数组
static BOOL _isConnectSuccess;
@implementation ZLUSBPlugInTool
+ (void)load {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidConnect:) name:EAAccessoryDidConnectNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidDisconnect:) name:EAAccessoryDidDisconnectNotification object:nil];
[[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];
_accessoryList = [[NSMutableArray alloc] initWithArray:[[EAAccessoryManager sharedAccessoryManager] connectedAccessories]];
// 已连接上配件 - 已经插上硬件,才打开app(通知是无效的,因为还未进入界面)
if (_accessoryList.count) {
_isConnectSuccess = YES;
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:kProbeKey];
} else {
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:kProbeKey];
}
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:EAAccessoryDidConnectNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:EAAccessoryDidDisconnectNotification object:nil];
_accessoryList = nil;
}
#pragma mark - 通知配件连接成功(突然插上)
+ (void)_accessoryDidConnect:(NSNotification *)notification {
_isConnectSuccess = YES;
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:kProbeKey];
// 连接成功通知
[[NSNotificationCenter defaultCenter] postNotificationName:kIsConnectSuccessNotificationAndKey object:nil userInfo:@{kIsConnectSuccessKey:@(YES)}];
}
#pragma mark - 通知配件断开连接(突然拔掉的情况)
+ (void)_accessoryDidDisconnect:(NSNotification *)notification {
_isConnectSuccess = NO;
// 断开通知
[[NSNotificationCenter defaultCenter] postNotificationName:kIsConnectSuccessNotificationAndKey object:nil userInfo:@{kIsConnectSuccessKey:@(NO)}];
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:kProbeKey];
}
+ (BOOL)isConnectSuccess {
return _isConnectSuccess;
}
网友评论