开始的一些话
作为一个“半路出家”的iOS的程序猿,一直使用OC开发,也想过使用Swift,但一直没有时间和机会;但最近做了一个新的项目,为我提供了机会,整个App大部分使用了Swift进行编写。体会就是Swift是真的很简练,入门也比较容易。
现在开发基本完成,于是准备把这次开发中用到的一些知识总结出来,写的不好,还请见谅!
第一个是Swift实现的二维码扫描,支持扫码和自动识别相册中的二维码图片,内容没有太多废话,直接上效果图和源码。
效果图
源码
import UIKit
import AVKit
protocol QRScanDelegate {
func handleQRScanResult(result: String);
}
class QRScanViewController: UIViewController {
var delegate: QRScanDelegate?
var lampBtn: UIButton!
var lampImgView: UIImageView!
var lampTitleLab: UILabel!
var albumBtn: UIButton!
var captureDevice: AVCaptureDevice?
var captureInput: AVCaptureDeviceInput?
var mataOutput: AVCaptureMetadataOutput?
var captureSession: AVCaptureSession?
var capturePreView: AVCaptureVideoPreviewLayer?
var scanView: UIImageView?
var torchTag = false
lazy var interestRect: CGRect = {
let kPadding: CGFloat = 60
let rectLength = kScreenWidth - kPadding * 2
let rect = CGRect.init(x: kPadding,
y: (kScreenHeight - rectLength) / 2 - 60,
width: rectLength,
height: rectLength)
return rect
}()
override func viewDidLoad() {
super.viewDidLoad()
setupCoverView()
setupInterestRectBoard()
setupScanLine()
setupTopView()
setupBottomView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupCaptureSession()
startScan()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if torchTag {
try? captureDevice?.lockForConfiguration()
captureDevice?.torchMode = .off
captureDevice?.unlockForConfiguration()
torchTag = false
}
}
// MARK: - 开始扫描
func startScan() {
scanView?.isHidden = false
let animation = CABasicAnimation.init(keyPath: "transform.translation.y")
animation.fromValue = 0
animation.toValue = self.interestRect.size.height
animation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.duration = 3
animation.isRemovedOnCompletion = false
animation.repeatCount = MAXFLOAT
scanView?.layer.add(animation, forKey: "y_transaltion")
if ((captureSession?.isRunning)!) {
return
}
captureSession?.startRunning()
}
// MARK: - 停止扫描
func endScan() {
if (!(captureSession?.isRunning)!) {
return
}
captureSession?.stopRunning()
scanView?.isHidden = true
scanView?.layer.removeAnimation(forKey: "y_transaltion")
}
func setupScanLine() {
scanView = UIImageView.init(frame: CGRect(x: self.interestRect.origin.x+1,
y: self.interestRect.origin.y+1,
width: