iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 29
0

在ios7之前,要掃描QR code必須要用到第三方程式,但現在ios已經內建這項功能。
這次我們要用到 “AVCaptureSession” 這個類別並且偵測裝置中的相機

  1. 在 < info.plist > 中建立相機、相簿的使用權限

  2. 建立一個新的類別: “DeviceInput”,並且繼承 “NSObject”

  3. 在 < DeviceInput.swift >
    匯入 “AVFoundation”

import AVFoundation

宣告 input 相關輸入方式

class DeviceInput: NSObject {
    //declared the input device
    var frontWildAngleCamera : AVCaptureDeviceInput? //frontwildAngleCamera
    var backWildAngleCamera: AVCaptureDeviceInput? // backwildAngleCamera
    var backTelephotoCamera: AVCaptureDeviceInput? //backtelephotoCamera
    var backDualCamera: AVCaptureDeviceInput? // dual camera
  1. 取得所有 camera 相關裝置,並且放到對應變數中
//get all the camera type
func getAllCameras() {
    
    let cameraDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInTelephotoCamera, .builtInDualCamera],mediaType: .video,  position: .unspecified).devices
            for camera in cameraDevices {
                let inputDevice = try! AVCaptureDeviceInput(device: camera)
                
                if camera.deviceType == .builtInWideAngleCamera, camera.position == .front {
                    frontWildAngleCamera = inputDevice
                }
                if camera.deviceType == .builtInWideAngleCamera, camera.position == .back {
                    backWildAngleCamera = inputDevice
                }
                if camera.deviceType == .builtInTelephotoCamera {
                    backTelephotoCamera = inputDevice
                }
                if camera.deviceType == .builtInDualCamera {
                    backDualCamera = inputDevice
                }
            }
        }
  1. 重新複寫初始化設定
override init() {
        super.init()
        getAllCameras()
} 

上一篇
UIImagePickerController and Camera (一) ( D day + 27 )
下一篇
QR code scanner and AVCaptureSession (二) ( Final )
系列文
挑戰 30天內送審一支APP 30

尚未有邦友留言

立即登入留言