iOS - Issue with displaying battery status [duplicate] - iphone

This question already has answers here:
How to get battery status?
(5 answers)
Closed 9 years ago.
I am trying to display battery percentage with UILabel , but the result is nonsense ! here is my code :
UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
int i=[myDevice batteryState];
_battery.text = [NSString stringWithFormat:#"%i",i];
the labels shows number 2 !!!!

Use below code to get battery level
UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batteryLevel = [myDevice batteryLevel];
_battery.text = [NSString stringWithFormat:#"%f",batteryLevel*100];
[myDevice batteryLevel]; will give you the battery between 0.0 (empty) and 1.0 (100% charged)
Hope it helps..

iPhone OS provides two type of battery monitoring events, one for when the state changes (e.g., charging, unplugged, full charged) and one that updates when the battery’s charge level changes. As was the case with proximity monitoring, you register callbacks to receive notifications:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(batteryChanged:) name:#"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(batteryChanged:) name:#"UIDeviceBatteryStateDidChangeNotification" object:device];
ALso refer this link.

[myDevice batteryState];//return is a variable of UIDeviceBatteryState
the labels shows number 2 means"UIDeviceBatteryStateCharging, // plugged in, less than 100%",if you want to display battery percentage. The code in the first answer will help you.

Related

Get iPhone physical color using the API [duplicate]

This question already has answers here:
Detecting Color of iPhone/iPad/iPod touch?
(6 answers)
Closed 9 years ago.
After iPhone 5c announcement, i'm curious if anybody knows an API how to get an iPhone 5c colour? I'm sure everyone will find it convenient loading a corresponding UI colour scheme to the device colour.
I'm thinking about wrapping it in something like the UIDevice category, which will return a UIColor.
Update:
#ColinE and #Ortwin Gentz
has indicated the availability of private UIDevice instance method calls for it.
Please note, that in case of iPhone 5c, what you are really looking for is deviceEnclosureColor, as deviceColor will always return #3b3b3c, as it is a front colour.
method signature:
-(id)_deviceInfoForKey:(struct __CFString { }*)arg1
UIDevice category for it:
#interface UIDevice (deviceColour)
- (id)_deviceInfoForKey:(struct __CFString { }*)arg1;
- (NSString*)deviceColourString_UntilAppleMakesItPublic;
- (NSString*)deviceEnclosureColour_UntilAppleMakesItPublic;
#end
#implementation UIDevice (deviceColour)
- (NSString*)deviceColourString_UntilAppleMakesItPublic
{
return [self _deviceInfoForKey:#"DeviceColor"];
}
- (NSString*)deviceEnclosureColour_UntilAppleMakesItPublic
{
return [self _deviceInfoForKey:#"DeviceEnclosureColor"];
}
#end
The device colour (used to?) be encoded in the serial number of the device. I don't have a device to test on with them not officially released yet, but I imagine the solution will be similar to this:
Typical format of the iPhone SN is as follows: AABCCDDDEEF
AA = Factory and Machine ID B = Year of Manufacturing (9 is
2009/2019, 0 is 2010/2020, 1 is 2011 and so on) CC = Production
Week (01 is week 1 of B, 11 is week 11 of B and so on) DDD =
Unique Identifier EE = Color (A4=black) F = size (S=16GB,
T=32GB)
[Source]
There is more information on old techniques here
I would like to point out however, that I expect there isn't a supported method of getting the serial number. Assuming you'd only like to know this information so that you can customise your UI, I'd just put in a user option or ask them to select the colour of their device on first startup (or some other early point in the app-user life)
There's a private API to retrieve both the DeviceColor and the DeviceEnclosureColor. In case of the iPhone 5c, the interesting part is the enclosure color (the device color = front color is always #3b3b3c).
UIDevice *device = [UIDevice currentDevice];
SEL selector = NSSelectorFromString(#"deviceInfoForKey:");
if (![device respondsToSelector:selector]) {
selector = NSSelectorFromString(#"_deviceInfoForKey:");
}
if ([device respondsToSelector:selector]) {
NSLog(#"DeviceColor: %# DeviceEnclosureColor: %#", [device performSelector:selector withObject:#"DeviceColor"], [device performSelector:selector withObject:#"DeviceEnclosureColor"]);
}
I've blogged about this and provide a sample app:
http://www.futuretap.com/blog/device-colors/
Warning: As mentioned, this is a private API. Don't use this in App Store builds.
A number of people on Twitter have cited the following method:
[[UIDevice currentDevice] _deviceInfoForKey:#"DeviceColor"]
Although I have not confirmed it myself.
This may help you...
UIDevice *device = [UIDevice currentDevice];
SEL selector = NSSelectorFromString([device.systemVersion hasPrefix:#"7"] ? #"_deviceInfoForKey:" : #"deviceInfoForKey:");
if ([device respondsToSelector:selector]) {
NSLog(#"DeviceColor: %# DeviceEnclosureColor: %#",
[device performSelector:selector withObject:#"DeviceColor"],
[device performSelector:selector withObject:#"DeviceEnclosureColor"]);
}
Ref: Detecting Color of iPhone/iPad/iPod touch?

How to Detect Flip of iPhone?

is there a logic to detect if the user has flipped their phone like from battery side to screen side and vice versa in horizontal plane? I have tried getting raw values to determine if the device is in the horizontal position on both faces but how to detect the whole motion , could someone point me in right direction.
If you take a look at the UIDevice class reference, you'll see the orientation enum. Two of it's values are UIDeviceOrientationFaceDown and UIDeviceOrientationFaceUp. That being said, all you have to do is register an observer to the UIDeviceOrientationDidChangeNotification notification, and upon call you can check the devices current orientation and handle this accordingly.
[[NSNotificationCenter defaultCenter] addObserverForName:UIDeviceOrientationDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationFaceDown) {
// device facing down
}else if (orientation == UIDeviceOrientationFaceUp) {
// device facing up
}else{
// facing some other direction
}
}];
Be sure to use the following to start generating the device notifications you'll need to observe.
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
If you want to get more specific information about the orientation of the device, you'll need to use the Core Motion framework to get gyro data directly. With this, you can track the exact current direction the device is facing in 3D space.
_motionManager = [CMMotionManager new];
NSOperationQueue *queue = [NSOperationQueue new];
[_motionManager setGyroUpdateInterval:1.0/20.0];
[_motionManager startGyroUpdatesToQueue:queue withHandler:^(CMGyroData *gyroData, NSError *error) {
NSLog(#"%#",gyroData);
}];

Currency symbol not updating came from Background iPhone?

Am getting the device local currency symbol by using this code.
NSLocale *theLocale = [NSLocale currentLocale];
NSString *symbol = [theLocale objectForKey:NSLocaleCurrencySymbol];
NSLog(#"Symbol : %#",symbol);
NSString *code = [theLocale objectForKey:NSLocaleCurrencyCode];
NSLog(#"Code : %#",code);
When the app restart the currency symbol changing but when the app from background the currency symbol not updating.
In iPhone setting i have changed the region United States and launched the app the currency symbol show "$".
When i have change the region India and get the app from Background and call the same code it shows again "$". The currency symbol not updating. When i came back and reenter into the screen the currency symbol updating to India symbol.
In appDelegate:
- (void)applicationWillEnterForeground:(UIApplication *)application:
[[NSNotificationCenter defaultCenter] postNotificationName:#"CurrencyUpdated" object:nil];
In sampleViewController: viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reloadCurrencySymbol) name:#"CurrencyUpdated" object:nil];
In sampleViewController:
-(void) reloadCurrencySymbol
{
NSLocale *theLocale = [NSLocale currentLocale];
NSString *symbol = [theLocale objectForKey:NSLocaleCurrencySymbol];
NSLog(#"Symbol : %#",symbol);
NSString *code = [theLocale objectForKey:NSLocaleCurrencyCode];
NSLog(#"Code : %#",code);
}
Can anyone please help to solve this issue? Thanks in advance.
EDIT
I have recalled the [self viewDidLoad]; but the region has not changed. When i return to previous screen and again enter into the same screen the region is updating. Can anyone please help to solve this? Thanks.
in your sampleview controller add this in viewdidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reloadCurrencySymbol) name: UIApplicationDidBecomeActiveNotification object:nil];
this is the right way to reload your symbol when the app becomes active
Likely its similar to MacOSX where when you change the language you need to restart the app to get it to start with the new locale.
I'm guessing that you would need to quit first, and there's probably no other way around it.

Proximity Sensor is not working in iPhone 4 device

//I have created below snippet to let the sensor to be detected.
-(void)addProximitySensorControl {
UIDevice *device = [UIDevice currentDevice];
device.proximityMonitoringEnabled = YES;
BOOL state = device.proximityState;
if(state)
NSLog(#"YES");
else
NSLog(#"NO");
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(proximityChanged:)
name:#"UIDeviceProximityStateDidChangeNotification"
object:nil];
}
In the iPhone 3GS or earlier proximityChanged: method is called successfully but in iPhone 4 while I am hovering object from upwards the sensor(screen) its not being detected. Any idea Guys?
I can see a few problems with this code. The first is that you use
name:#"UIDeviceProximityStateDidChangeNotification"
instead of
name:UIDeviceProximityStateDidChangeNotification
Both work, but using the bare version will give you a compiler error if you make a typo. (You want to get a compiler error with typos, it prevents silent errors).
The next thing is that you aren't actually checking for the proximity sensor being available before adding the notification. Your code:
BOOL state = device.proximityState
But this just checks whether or not the device is close to the users face. What you really want is to set proximityEnabled to YES, then check that it actually got set. It's a little counterintuitive.
UIDevice *device = [UIDevice currentDevice];
[device setProximityMonitoringEnabled:YES];
if ([device isProximityMonitoringEnabled]) {
// Do your stuff
}
Here's a full code sample:
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
UIDevice *device = [UIDevice currentDevice];
// Register for proximity notifications
[device setProximityMonitoringEnabled:YES];
if ([device isProximityMonitoringEnabled]) {
[notificationCenter addObserver:self
selector:#selector(proximityChanged:)
name:UIDeviceProximityStateDidChangeNotification
object:device];
} else {
NSLog(#"No Proximity Sensor");
}
Apple Docs: "Not all iOS devices have proximity sensors. To determine if proximity monitoring is available, attempt to enable it. If the value of the proximityMonitoringEnabled property remains NO, proximity monitoring is not available."
There is nothing wrong with your code (assuming that you did implement proximityChanged: of course). I tested your code on an iPhone 4 and it responds to my hand moving in front of the proximity sensor.
Maybe the hardware is slightly different on the 3GS, meaning it is more sensitive to what you are doing? Can you try on a different iPhone 4 device (or at least verify that the proximity sensor works at all e.g. by using the phone app)?
Check out this one :
http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIDevice_Class/Reference/UIDevice.html
You should always check whether the particular device have proximity sensor or not.
Not all iOS devices have proximity sensors.
BOOL state = device.proximityState;
if(state)
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(proximityChanged:)
name:#"UIDeviceProximityStateDidChangeNotification" object:nil];
else
NSLog(#"NO");

How to read battery case status from the iphone? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get battery status?
I am implementing one iPhone application in which i want to read battery status of the iPhone by programming. I dont know is it possible or not. Please give me advice for that.
To read battery level and status you just have to:
float battLvl = [[UIDevice currentDevice] batteryLevel]; // range is from 0.0 to 1.0
UIDeviceBatteryState battState = [UIDevice currentDevice] batteryStatus];
To monitor battery level and status you can do the following:
// enable monitoring and add observers with selector
UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(batteryChanged:) name:#"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(batteryChanged:) name:#"UIDeviceBatteryStateDidChangeNotification" object:device];
// Your notification handler
- (void)batteryChanged:(NSNotification *)notification
{
UIDevice *device = [UIDevice currentDevice];
NSLog(#"state: %i | charge: %f", device.batteryState, device.batteryLevel);
}
Following lines of code will be helpful:
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
[[UIDevice currentDevice] batteryLevel];
[[UIDevice currentDevice] batteryState];
For detail, refer THIS link. It will elaborate you.