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

时间:2015-07-14 17:44:23

标签: swift notifications watchkit apple-watch battery

我正在制作Apple Watch应用,让您看到iPhone电池电量, 这是获取电池电量的代码:

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

现在,当iPhone电池电量为10%时,如何拨打通知? 感谢

1 个答案:

答案 0 :(得分:1)

这是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];