代码基于:swift3.0
题外话:虽然之前对swift有所了解,但是,长时间不敲swift代码,生疏的非常快。告诫自己,不停的敲敲敲,嗯。
新手总结
这里只实现了很基本的东西,主要是熟悉swift代码
- 开关手电筒
//控制开、关
@IBAction func actionTorch(_ sender: UIButton) {
print("torch click")
sender.isSelected = !sender.isSelected
if sender.isSelected {
openTorch(lightLevel: lightLevel)
}else {
closeTorch()
}
}
//开
func openTorch(lightLevel: Float) -> Void {
guard let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) else {
print("no AVCaptureDevice")
return
}
guard ((try? device.lockForConfiguration()) != nil) else {
print("deviece.lockForConfiguration error")
return
}
if device.hasTorch {
guard ((try? device.setTorchModeOnWithLevel(lightLevel)) != nil) else {
print("device.setTorchModeOnWithLevel(lightLevel)")
return
}
}
device.unlockForConfiguration()
}
//关
func closeTorch() -> Void {
guard let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) else {
print("no device")
return
}
guard ((try? device.lockForConfiguration()) != nil) else {
print("deviece.lockForConfiguration error")
return
}
if device.hasTorch {
device.torchMode = .off
}
device.unlockForConfiguration()
}
- 闪烁
@IBAction func actionFlash(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
//flash
torchBtn.isSelected = true
flashTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.flashTorch), userInfo:nil, repeats: true)
}else {
//end flash
flashTimer.invalidate()
torchBtn.isSelected = false
closeTorch()
ViewController.i = 0
}
}
//怎么闪烁呢,就是定时器不断地调,奇数就开,偶数就关
func flashTorch() -> Void {
ViewController.i += 1;
print(ViewController.i)
if ViewController.i%2 == 1 {
openTorch(lightLevel: lightLevel)
}else {
closeTorch()
}
}
- 改变光线
@IBAction func actionChageLight(_ sender: UISlider) {
lightLevel = sender.value
torchBtn.isSelected = true
openTorch(lightLevel: lightLevel)
}
手电筒
后面有时间,会继续更新新的功能
手电筒GitHub地址
遇到的一些问题
- 拖线的时候报错,“could not insert new action connection could not find any information for the class named”。 如下图。我的解决方案:重启xcode
xcode关掉之后再次打开自己的项目,发现脱线的方法不执行。 我的解决方案:拖线的方法前面变成了空心的圈圈,重新绑定就行了
-
不能声明静态的int变量,报错"Static properties may only be declared on a type" 。如下图
原因:搜索到一个回答 Swift supports static variable without having it attached to a class/struct. Try declaring a private struct with static variable. Type properties and methods belong to a type (i.e. a Class, Struct or Enum) and cannot belong to a function alone
解决:放在类里面,不要放在方法里面
4.处理异常
guard ((try? device.lockForConfiguration()) != nil) else {
print("deviece.lockForConfiguration error")
return
}
函数后面带throws的都要对异常进行处理,不处理会报错,swift真的是很安全啊,一点点问题写错,就直接报错,这样也好,提前做好检查。我喜欢用这种方式捕获异常,如果有错误发生,方法会返回nil,会进入guard大括号里面的方法,没发生错误,就直接往下执行啦。
这里随便给出捕获异常的几种方法:处理异常的三种方式
了解就好了,最好用最安全的方式,就是我这种啦。。