swift - 如何在 iPhone 电池电量为 10% 时收到通知

标签 swift notifications watchkit apple-watch battery

我正在构建一个 Apple Watch 应用程序,让您可以看到 iPhone 电池电量, 这是获取电池电量的代码:

 UIDevice.currentDevice().batteryMonitoringEnabled = true
 batteryLevel = UIDevice.currentDevice().batteryLevel

现在如何在 iPhone 电池电量为 10% 时调用通知? 谢谢

最佳答案

这是 Objective-C 但很容易翻译成 Swift:

    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    float battery = [[UIDevice currentDevice] batteryLevel];

    if (battery < alertLevel) {
        //Send notification   
    }

如何发送 UILocalNotification

        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
        notification.alertBody = @"WARNING!";
        notification.timeZone = [NSTimeZone defaultTimeZone];
        notification.soundName = UILocalNotificationDefaultSoundName;
        notification.applicationIconBadgeNumber = 0;
        NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"Low battery!" forKey:@"Notification"];
        notification.userInfo = infoDict;
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];

关于swift - 如何在 iPhone 电池电量为 10% 时收到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31413715/

相关文章:

ios - 从我的 watch 应用程序发送文本

swift - 从 Realm 数组中查询特定结果

ios - ios中sqlite的最大大小限制是多少

android - BroadcastReceiver 中 onReceive 方法中关于 Intent null 的附加信息

javascript - jqTouch/JavaScript 警报 - 如何删除标题?

ios - 我应该使用哪种方法将数据发送到 Apple Watch 并返回?

ios - Apple Watch 无法将数据传递至 iPhone - Swift

ios - 使用自定义起点接收有限查询

swift - 添加 Firebase iOS SDK(4.3.0 或更高版本)或 Unity 插件(6.15.0 或更高版本),然后构建、运行和崩溃您的应用

Android 通知图标是一个白色圆圈