gpt4 book ai didi

ios - 在 Objective-C 中如何检测 iPhone 和 iPad 何时插入?

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:03:37 26 4
gpt4 key购买 nike

我在网上找到了一些关于检测电池充电状态变化的教程,但我需要检测的是 iphone/ipad 插入的第二个。未插入然后发送充电更新。

如果电池电量低于 25%,我们需要阻止他们使用我们的应用程序,但如果插入电源,则我们需要允许他们使用。

我都使用了这两个,但是在插入或拔出时都不会触发通知。

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.



// tell the device that - my application is going to monitor Device Battery levels
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

// schedule a timer to update the battery details
[NSTimer scheduledTimerWithTimeInterval:600.0
target:self
selector:@selector(updateBatteryDetails)
userInfo:nil
repeats:YES];

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

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(pluggedDetected)
name:UIDeviceBatteryStateDidChangeNotification
object:nil];
}

最佳答案

代码的一个问题是,当您注册通知时,您传递的是一个不带任何参数的选择器。作为the docs for NSNotificationCenter告诉我们:

The method specified by notificationSelector must have one and only one argument (an instance of NSNotification).

修复导致您的代码对我有用的问题。您的方法应如下所示:

- (void)pluggedDetected:(NSNotification*)notification
{
//...
}

添加观察者的调用应该如下所示:

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(pluggedDetected:)
name:UIDeviceBatteryStateDidChangeNotification
object:nil];

请注意,冒号是选择器名称的重要组成部分。

鉴于您正在使用通知来检测变化,我认为您不需要定时器来更新电池信息——只要通知触发您的方法就这样做。

关于ios - 在 Objective-C 中如何检测 iPhone 和 iPad 何时插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26266047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com