1

I want to know if its possible to detect when USB is connected to iPhone device programmatically through private or public frameworks.

I know we can detect this by using UIDeviceBatteryState, but in that case it will only detect charging, unplugged, or not charging states, and will not be able to identify if its charging through USB connected via power source directly or through any other device like mac or any other machine.

Please let me know.

Jas_meet
  • 366
  • 1
  • 20

1 Answers1

6

You can detect it like so. No need for private APIs

static void _callback(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
    if ([(__bridge NSString*)name isEqualToString:@"com.apple.mobile.lockdown.host_attached"])
    {
        NSLog(@"USB connected");
    }
    else if ([(__bridge NSString*)name isEqualToString:@"com.apple.mobile.lockdown.host_detached"])
    {
        NSLog(@"USB disconnected");
    }
}

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, _callback, CFSTR("com.apple.mobile.lockdown.host_attached"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, _callback, CFSTR("com.apple.mobile.lockdown.host_detached"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
creker
  • 9,400
  • 1
  • 30
  • 47
  • this notification is not working on iOS 12. Have you found any alternative for this? – Abilash Bansal Jun 26 '19 at 07:01
  • 1
    I know this is an old question but can you detect the current state, in case I run the app while it's connected it will not call the attached notification ? FYI @AbilashBansal its working with me iOS version 12.2 – Aziz Jul 29 '19 at 18:29