Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple helper class to check and get notified if a USB device is connected/disconnected
// erkanyildiz
// 20160311-1158
//
// EYUSBDeviceConnectivity.h
#import <Foundation/Foundation.h>
@interface EYUSBDeviceConnectivity : NSObject
+ (instancetype)sharedInstance;
@property (nonatomic, copy) void (^onDeviceConnect)(NSNotification* notification);
@property (nonatomic, copy) void (^onDeviceDisconnect)(NSNotification* notification);
@property (nonatomic, readonly) BOOL isDeviceConnected;
@end
// erkanyildiz
// 20160311-1158
//
// EYUSBDeviceConnectivity.m
#import "EYUSBDeviceConnectivity.h"
#import <ExternalAccessory/ExternalAccessory.h>
@implementation EYUSBDeviceConnectivity
+ (instancetype)sharedInstance
{
static EYUSBDeviceConnectivity *s_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{s_sharedInstance = self.new;});
return s_sharedInstance;
}
- (instancetype)init
{
if (self = [super init])
{
[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];
//NOTE: check if device already connected on app launch, if so post notification manually
if([self isDeviceConnected])
{
EAAccessory* accessory = EAAccessoryManager.sharedAccessoryManager.connectedAccessories.firstObject;
//NOTE: supposing only one accessory is connected
NSNotification* notification = [NSNotification notificationWithName:EAAccessoryDidConnectNotification object:EAAccessoryManager.sharedAccessoryManager userInfo:@{@"EAAccessoryKey":accessory}];
//NOTE: to make sure it is performed on next run loop, so blocks will be set.
[self performSelector:@selector(accessoryDidConnect:) withObject:notification afterDelay:0.0];
}
}
return self;
}
- (BOOL)isDeviceConnected
{
return EAAccessoryManager.sharedAccessoryManager.connectedAccessories.count > 0;
}
- (void)accessoryDidConnect:(NSNotification*)aNotification
{
if(self.onDeviceConnect)
{
self.onDeviceConnect(aNotification);
}
}
- (void)accessoryDidDisconnect:(NSNotification*)aNotification
{
if(self.onDeviceDisconnect)
{
self.onDeviceDisconnect(aNotification);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.