2016-11-02 5 views
0

장치가 USB 포트에 연결되거나 USB 포트에서 분리 될 때마다 알림을 받아야하는 Cocoa 앱이 있습니다. DeviceConnected 콜백이 작동하도록 할 수 있지만 USB 장치를 분리 할 때 DeviceDisconnected 함수가 호출되지 않습니다.USB 장치 자동 감지 연결/연결 해제

+ (void)listenForUSBEvents 
{ 
    io_iterator_t portIterator = 0; 
    CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName); 
    IONotificationPortRef notifyPort = IONotificationPortCreate(kIOMasterPortDefault); 
    CFRunLoopSourceRef runLoopSource = IONotificationPortGetRunLoopSource(notifyPort); 
    CFRunLoopRef runLoop = CFRunLoopGetCurrent(); 

    CFRunLoopAddSource(runLoop, runLoopSource, kCFRunLoopDefaultMode); 
    CFRetain(matchingDict); 

    kern_return_t returnCode = IOServiceAddMatchingNotification(notifyPort, kIOMatchedNotification, matchingDict, DeviceConnected, NULL, &portIterator); 

    if (returnCode == 0) 
    { 
     DeviceConnected(nil, portIterator); 
    } 

    returnCode = IOServiceAddMatchingNotification(notifyPort, kIOMatchedNotification, matchingDict, DeviceDisconnected, NULL, &portIterator); 

    if (returnCode == 0) 
    { 
     DeviceDisconnected(nil, portIterator); 
    } 
} 

@end 


void DeviceConnected(void *refCon, io_iterator_t iterator) 
{ 
    kern_return_t returnCode = KERN_FAILURE; 
    io_object_t usbDevice; 

    while ((usbDevice = IOIteratorNext(iterator))) 
    { 
    io_name_t name; 

    returnCode = IORegistryEntryGetName(usbDevice, name); 

    if (returnCode != KERN_SUCCESS) 
    { 
     return; 
    } 

    [[NSNotificationCenter defaultCenter] postNotificationName:deviceConnectedNotification object:nil userInfo:nil]; 
    } 
} 

void DeviceDisconnected(void *refCon, io_iterator_t iterator) 
{ 
    [[NSNotificationCenter defaultCenter] postNotificationName:deviceDiconnectedNotification object:nil userInfo:nil]; 
} 

답변

0

는 내가 잘못하고 있었는지 알아 냈 :

다음은 내 코드입니다. 모든

첫째, deviceDisconnected에 대한 IOServiceAddMatchingNotification은 다음과 같아야합니다

returnCode = IOServiceAddMatchingNotification(notifyPort, kIOTerminatedNotification, matchingDict, DeviceDisconnected, NULL, &portIterator); 

둘째는 DeviceDisconnected 기능은 다음과 같아야합니다

void DeviceDisconnected(void *refCon, io_iterator_t iterator) 
{ 
    kern_return_t returnCode = KERN_FAILURE; 
    io_object_t  usbDevice; 

    while ((usbDevice = ioIteratorNext(iterator))) 
    { 
     returnCode = IOObjectRelease(usbDevice); 

     if (returnCode != kIOReturnSuccess) 
     { 
      NSLog(@"Couldn't release raw device object: %08x.", returnCode); 
     } 
    } 

    [[NSNotificationCenter defaultCenter] postNotificationName:deviceDiconnectedNotification object:nil userInfo:nil]; 
}