arcade16 arcade16 - 2 months ago 10
iOS Question

Call Objective-C Method from complex C Method?

I have set up a group of methods to dim and brighten the screen of the device, as well as introduce a black UIView over the view, when the device is charging / not charging.

The challenge I am having is calling my Obj C methods (brightenScreen and dimScreen) from the C method that is used to check if the device is charging.

Any input / help would be appreciated!

-(void)setUpChargingCheck{

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

// Do whatever you want...
if ([[UIDevice currentDevice] batteryState] != UIDeviceBatteryStateUnplugged){
[self brightenScreen];
}else{
[self dimScreen];
}

// Registering for a specific notification
NSString *notificationName = @"com.apple.springboard.fullycharged";
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
NULL,
yourCustomMethod,
(__bridge CFStringRef)notificationName,
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);

}

// The custom method that will receive the notification
static void yourCustomMethod(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
NSString *nameOfNotification = (__bridge NSString*)name;

if([nameOfNotification isEqualToString:@"com.apple.springboard.fullycharged"])
{
if ([[UIDevice currentDevice] batteryState] != UIDeviceBatteryStateUnplugged){
[[UIScreen mainScreen] setBrightness:1.0];
// brighten screen here
}else{
[[UIScreen mainScreen] setBrightness:0.0];
// dim screen here
}
}
}

-(void)dimScreen{
[[UIScreen mainScreen] setBrightness:1.0];
[self.blackoutView removeFromSuperview];
}

-(void)brightenScreen{
CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = [UIScreen mainScreen].bounds.size.height;

[[UIScreen mainScreen] setBrightness:0.0];
self.blackoutView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
[self.blackoutView setBackgroundColor:[UIColor blackColor]];
[self.view addSubview:self.blackoutView];
}

Answer
    YourClass *yourClassObject = (__bridge YourClass *)(observer);
    [yourClassObject dimScreen];
Comments