2012-02-15 40 views
5

有沒有辦法知道我的設備(iPhone)何時插入電源,例如帶有USB端口的電腦或汽車音響系統?我在我的應用中使用本地化服務,並且我想在設備插入時自動更改爲kCLLocationAccuracyBestForNavigation。謝謝...如何知道iOS設備何時插入?

回答

3

您可以註冊以在配件連接或斷開連接時收到通知。

例子:

[[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]; 

一旦你收到此通知,您可以使用一個for循環遍歷每個附件,如:

NSArray *accessories = [[EAAccessoryManager sharedAccessoryManager] connectedAccessories]; 
EAAccessory *accessory = nil; 

for (EAAccessory *obj in accessories) 
{ 
    // See if you're interested in this particular accessory 
} 

在某一點(的dealloc也許)你將要註銷爲這些通知。你可以做到這一點,如:

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

**非常感謝**我會tes t此代碼... – human4 2012-02-16 21:21:54

+0

@ human4總是樂於提供幫助。如果'UIDevice'的'batteryState'上的KVO正常工作,那麼這就是我想要的。 – Sam 2012-02-16 22:22:05

+0

這不再起作用。 – 2015-01-23 08:53:15

7

您可以啓用電池監控直通的UIDevice class並檢查電池狀態,看它是否正在充電:

typedef enum { 
    UIDeviceBatteryStateUnknown, 
    UIDeviceBatteryStateUnplugged, 
    UIDeviceBatteryStateCharging, 
    UIDeviceBatteryStateFull, 
} UIDeviceBatteryState; 

你要檢查或收費在啓用最佳GPS準確性之前已滿。通過讓你自己的操作方法batteryStateChanged通話

UIDeviceBatteryState batteryState = [[UIDevice currentDevice] batteryState]; 

要訂閱通知,關於電池狀態的變化,例如:

- (void) setup { 
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 
    NSNotificationCenter * center= [NSNotificationCenter defaultCenter]; 
    [center addObserver:self 
      selector:@selector(batteryStateChanged) 
       name:UIDeviceBatteryStateDidChangeNotification 
       object:nil]; 
} 

+1

+1在'UIDevice'的'batteryState'屬性上做KVO似乎是OP想要做的最好的方式。 – Sam 2012-02-15 21:04:38

+0

**非常感謝**我會測試此代碼... – human4 2012-02-16 21:21:37

2

要檢查電池狀態記得取消訂閱當你的對象是dealloced:

- (void) dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:NO]; 
} 
相關問題