How to know when iOS device is plugged in?

前端 未结 3 1952
闹比i
闹比i 2020-12-29 16:14

Is there a way to know when my device (iPhone) is plugged in to source power, like a computer or car audio systems with a USB port? I use localization services in my app and

3条回答
  •  不思量自难忘°
    2020-12-29 16:54

    You can register to be notified when an accessory connects or disconnects.

    Example:

    [[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self
                           selector:@selector(accessoryDidConnect:)
                               name:EAAccessoryDidConnectNotification
                             object:nil];
    [notificationCenter addObserver:self
                           selector:@selector(accessoryDidDisconnect:)
                               name:EAAccessoryDidDisconnectNotification
                             object:nil];
    

    Once you receive this notification you can use a for loop to go through each accessory like:

    NSArray *accessories = [[EAAccessoryManager sharedAccessoryManager] connectedAccessories]; 
    EAAccessory *accessory = nil; 
    
    for (EAAccessory *obj in accessories)
    { 
        // See if you're interested in this particular accessory
    }
    

    At some point (dealloc perhaps) you will want to unregister for these notifications. You can do this like:

    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self 
                                  name:EAAccessoryDidDisconnectNotification 
                                object:nil];
    [notificationCenter removeObserver:self 
                                  name:EAAccessoryDidConnectNotification 
                                object:nil];
    [[EAAccessoryManager sharedAccessoryManager] unregisterForLocalNotifications];  
    

提交回复
热议问题