簡體   English   中英

檢索電池電量僅在我第一次執行時有效

[英]Retrieving battery level only works the first time I do it

當我的應用程序首次啟動時,電池電量由float batteryLevel = [UIDevice currentDevice].batteryLevel正確檢索。 但是,當我稍后嘗試在我的代碼中檢索它時,即使電池電量發生變化,我也總是得到相同的值。

[UIDevice currentDevice].batteryLevel后續調用始終返回與第一個相同的結果,例如:如果我的應用程序啟動時電池電量為 30%,10 分鍾后我再次嘗試檢索它時,我得到 30% 作為好吧,但實際上,此時電池電量為 40%。

有誰知道為什么會發生這種情況?

監視不斷變化的電池電量您可以使用電池狀態通知UIDeviceBatteryStateDidChangeNotificationUIDeviceBatteryLevelDidChangeNotification

您可以注冊您的 VC 以接收更改通知,如下所示 -

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryStateDidChange:", name: UIDeviceBatteryStateDidChangeNotification, object: nil)
 NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelDidChange:", name: UIDeviceBatteryLevelDidChangeNotification, object: nil)   

然后實現選擇器方法

func batteryStateDidChange(notification: NSNotification){     
    // The stage did change: plugged, unplugged, full charge...
}

func batteryLevelDidChange(notification: NSNotification){     
   // The battery's level did change (98%, 99%, ...)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM