随时间改变 iPhone 手电筒强度 (Swift)
Changing iPhone flashlight intensity over time (Swift)
我想制作一个 iPhone 应用程序,在 Swift 中编程,它会随着时间的推移在不同强度之间改变手电筒。这样做的目的是复制一个低电量的手电筒。
我希望它像 "timeline" 一样,强度会在不同强度之间逐渐减弱,如下所示:
- 0 分钟时:100%
- 100 分钟时:0%
时不时地,我想让手电筒闪烁一点,让它看起来更像一个电量不足的手电筒。可能是这样的:
- 30 分钟时:70%
- 30分1秒时:100%
- 30分2秒时:70%
- 30分3秒时:20%
- 30分6秒时:70%
我读过如何打开手电筒, and how to make a timer (using NSTimer) here,但我不知道如何将它们结合起来以使手电筒强度随时间变化。
完成此任务的最佳方法是什么?
提前致谢!
使用功能setTorchModeOnWithLevel设置级别,您可以使用计时器设置级别更改的时间。
这是一个如何执行此操作的示例(在 brand-new iOS 单视图应用程序的 AppDelegate 中实现):
var timer: NSTimer?
func applicationDidBecomeActive(application: UIApplication) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "delayedAction", userInfo: nil, repeats: true)
}
let maxLightLevel = 5
var lightLevel = 5
func delayedAction() {
guard let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
else {
timer?.invalidate()
return
}
if let _ = try? device.lockForConfiguration() {
defer { device.unlockForConfiguration() }
if lightLevel == 0 {
timer?.invalidate()
device.torchMode = .Off
}
else {
try! device.setTorchModeOnWithLevel(Float(lightLevel)/Float(maxLightLevel))
}
--lightLevel
}
}
这段代码只是一个粗略的示例,应该添加适当的行为来处理切换应用、抛出的异常等。
我想制作一个 iPhone 应用程序,在 Swift 中编程,它会随着时间的推移在不同强度之间改变手电筒。这样做的目的是复制一个低电量的手电筒。
我希望它像 "timeline" 一样,强度会在不同强度之间逐渐减弱,如下所示:
- 0 分钟时:100%
- 100 分钟时:0%
时不时地,我想让手电筒闪烁一点,让它看起来更像一个电量不足的手电筒。可能是这样的:
- 30 分钟时:70%
- 30分1秒时:100%
- 30分2秒时:70%
- 30分3秒时:20%
- 30分6秒时:70%
我读过如何打开手电筒
完成此任务的最佳方法是什么?
提前致谢!
使用功能setTorchModeOnWithLevel设置级别,您可以使用计时器设置级别更改的时间。
这是一个如何执行此操作的示例(在 brand-new iOS 单视图应用程序的 AppDelegate 中实现):
var timer: NSTimer?
func applicationDidBecomeActive(application: UIApplication) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "delayedAction", userInfo: nil, repeats: true)
}
let maxLightLevel = 5
var lightLevel = 5
func delayedAction() {
guard let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
else {
timer?.invalidate()
return
}
if let _ = try? device.lockForConfiguration() {
defer { device.unlockForConfiguration() }
if lightLevel == 0 {
timer?.invalidate()
device.torchMode = .Off
}
else {
try! device.setTorchModeOnWithLevel(Float(lightLevel)/Float(maxLightLevel))
}
--lightLevel
}
}
这段代码只是一个粗略的示例,应该添加适当的行为来处理切换应用、抛出的异常等。