美文网首页
ios检测硬件端口是否连接配件(充电口连接配件检测)

ios检测硬件端口是否连接配件(充电口连接配件检测)

作者: 策马鞭程 | 来源:发表于2016-09-12 15:03 被阅读143次

    苹果官方提供Demo
    Demo地址下载

    IMG_1072.PNG

    工具类

    .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;
    }
    

    相关文章

      网友评论

          本文标题:ios检测硬件端口是否连接配件(充电口连接配件检测)

          本文链接:https://www.haomeiwen.com/subject/vappettx.html