UIInterfaceOrientationとUIDeviceOrientationは必ずしも一致しないので注意。特定の画面の向きをサポートしていない場合や、アプリを起動してからiPhoneを回転させていない場合などに、これらの値は一致しない。画面デザインに関することはUIDeviceOrientationを使うとうまくいく場合が多い。
//インターフェースの向き
UIInterfaceOrientation orientation =
[[UIApplication sharedApplication] statusBarOrientation];
//デバイスの向き
UIDeviceOrientation orientation =
[[UIDevice currentDevice] orientation];
インターフェースの向きが縦か横か判定するには以下のようにする。
if(UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])){
//縦置き(Portrait)の場合だけ実行される
}else{
//横置き(Landscape)の場合だけ実行される
}
if(UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])){
//横置き(Landscape)の場合だけ実行される
}else{
//縦置き(Portrait)の場合だけ実行される
}
バッテリーの残量は、以下のようにすれば取得できます。ただし、iPhone4Sで検証したところ、0.05(5%)刻みのデータしか取得できませんでした。iPhone自体は最低でも1%刻みのデータを持っているはずなので非公開APIを使うなどすれば、より詳細なデータが取れるはずです。
残量を取得する
以下のようにすればバッテリーの残量を取得できます。
[UIDevice currentDevice
].batteryMonitoringEnabled
= YES;
float batteryLevel
= [UIDevice currentDevice
].batteryLevel;
//バッテリー残量が変わったらbatteryLevelDidChangeにメッセージを送る
[[NSNotificationCenter defaultCenter
] addObserver
:self
selector
:@selector(batteryLevelDidChange
:)
name
:UIDeviceBatteryLevelDidChangeNotification object
:nil];
実行結果
2011-12-11 16:06:02.804 BatteryStatus[2004:707] -1.000000
2011-12-11 16:06:07.983 BatteryStatus[2004:707] 0.650000
2011-12-11 16:07:14.119 BatteryStatus[2004:707] -1.000000
2011-12-11 16:07:14.931 BatteryStatus[2004:707] 0.650000
2011-12-11 16:07:29.385 BatteryStatus[2004:707] 0.700000
2011-12-11 16:12:31.541 BatteryStatus[2004:707] 0.750000
2011-12-11 16:17:53.857 BatteryStatus[2004:707] 0.800000
2011-12-11 16:23:16.178 BatteryStatus[2004:707] 0.850000
充電ステータスを取得する
充電ステータスを取得するためには以下のように記述します。
[UIDevice currentDevice
].batteryMonitoringEnabled
= YES;
[UIDevice currentDevice
].batteryState;
//バッテリーの充電ステータスが変わったらbatteryLevelDidChangeにメッセージを送る
[[NSNotificationCenter defaultCenter
] addObserver
:self
selector
:@selector(batteryStateDidChange
:)
name
:UIDeviceBatteryStateDidChangeNotification object
:nil];
取得される値は以下の4種類です。
UIDeviceBatteryStateUnknown 不明
UIDeviceBatteryStateUnplugged 放電中
UIDeviceBatteryStateCharging 充電中
UIDeviceBatteryStateFull 満タン状態で、電源に接続されている
バッテリー残量を活かしたアプリの例
『ざっくりバッテリー』
公式サンプルプログラム
BatteryStatus
iPhoneアプリ開発に関する情報を公開中 ソースコードもあるよ。