UISwitch打开时如何获取本地通知?

时间:2014-03-12 08:16:06

标签: ios objective-c

我是iOS开发的初学者。我现在正在我的大学项目中开发一个电池实用程序。在我的“设置”列中,我可以选择让用户打开或关闭是否要在电池充满电时收到通知。当开关打开时,我遇到了获取本地通知的问题。当我试图关闭开关并在电池电量== 1.0时将其打开时,我才会收到警报视图。感谢有人可以帮助我。 :)

这是我的代码:

- (无效)notifySwitched {

if([self.notifyFullyChargedSwitch isOn])
{
    float batterylevel = [UIDevice currentDevice].batteryLevel;

    [UIDevice currentDevice].batteryMonitoringEnabled = YES;

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];

    [self notifyFullyCharged];
}

}

- (无效)notifyFullyCharged {

float batterylevel = [UIDevice currentDevice].batteryLevel;

if(batterylevel == 1.0){

    // Schedule the notification
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    //localNotification.fireDate = pickerDate;
    localNotification.alertBody = @"Unplug your device. Your battery has been fully charged.";
    localNotification.alertAction = @"Slide to view";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

}

1 个答案:

答案 0 :(得分:0)

只有当开关第一次打开时,代码才会实际添加观察者。将以下代码移动到任何初始化方法示例: - ViewDownload,应该添加观察者而不管切换状态。

[UIDevice currentDevice].batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];

然后在batteryLevelChanged方法中,需要在显示警报之前检查开关状态条件。

希望这有帮助。