Accessing the battery level on your iOS device

Posted by on in Programming

I recently saw a question on our forums on how to access the current battery level on an iOS device using FireMonkey, so I thought I would do a quick post about it. This sample code extends the DeviceInfo code snippet included with RAD Studio 10.1 Berlin Anniversary Edition.


 

unit uMain;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.ListBox,
  FMX.Layouts, FMX.Controls.Presentation;

type
  TDeviceInfoForm = class(TForm)
    btnGetDeviceInfo: TButton;
    ListBox1: TListBox;
    lbOSName: TListBoxItem;
    lbOSVersion: TListBoxItem;
    ToolBar1: TToolBar;
    Label1: TLabel;
    lbDeviceType: TListBoxItem;
    lblBatteryLevel: TListBoxItem;
    procedure btnGetDeviceInfoClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  DeviceInfoForm: TDeviceInfoForm;

implementation
{$IFDEF IOS}
uses
  iOSapi.UIKit, iOSapi.Foundation, Macapi.Helpers;
{$ENDIF}

{$R *.fmx}

{$IFDEF IOS}
procedure TDeviceInfoForm.btnGetDeviceInfoClick(Sender: TObject);
var
  Device : UIDevice;
begin
  Device := TUIDevice.Wrap(TUIDevice.OCClass.currentDevice);
  lbOSName.Text := Format('OS Name: %s', [NSStrToStr(Device.systemName)]);
  lbOSVersion.Text := Format('OS Version: %s', [NSStrToStr(Device.systemVersion)]);
  lbDeviceType.Text := Format('Device Type: %s', [NSStrToStr(Device.model)]);

//code added for detecting battery level
  Device.setBatteryMonitoringEnabled(True);
  lblBatteryLevel.Text := Format ('Battery Level: %d', [Round(Device.batteryLevel*100)]);
end;
{$ENDIF}


end.

 

 

 

 



About
Gold User, Rank: 5, Points: 558
Senior Product Manager, RAD Studio

Comments

  • Thierry G38500
    Thierry G38500 Friday, 19 May 2017

    Thanks for this great example !

    In the same way, is possible to know if the battery is charging ?

  • Mike Smith
    Mike Smith Tuesday, 18 April 2017

    I also know the same question how I can access the battery level in IOS system? I also contact to the iPhone app development company but they do not reply me of my question.
    I was posted this question on the many forums and question answering site like quora or ask but no one gives me the proper answer to my question, then suddenly I jump it to on your site and I found the answer to my question. I really thankful to share this stuff on your website. https://www.ingic.ae/ios-app-development/

  • Please login first in order for you to submit comments
  • Page :
  • 1

Check out more tips and tricks in this development video: