如何在 Swift 中使用前置攝像頭?


要使用 Swift 中的前置攝像頭,我們首先需要獲取我們正在使用的裝置中可用的攝像頭列表。在本文中,我們將看到如何獲取裝置列表,然後檢查是否存在前置攝像頭。我們將逐步完成它。

匯入 AVFoundation

檢查攝像頭列表是否存在

如果存在,則篩選前置攝像頭。

guard let frontCamera = AVCaptureDevice.devices().filter({ $0.position == .front })
.first as? AVCaptureDevice else {
   fatalError("Front camera not found")
}

AVCapture 的 devices() 方法返回了裝置列表。從此攝像頭列表中,我們將使用 filter 函式,在其中我們將檢查位置是否是前置攝像頭。我們可以將此轉換為函式並使用前置攝像頭。

func checkCamera() {
   guard let frontCamera = AVCaptureDevice.devices().filter({ $0.position == .front })
   .first as? AVCaptureDevice else {
      fatalError("Front camera not found")
   }
}

注意 − 這無法在模擬器上執行,因為模擬器沒有攝像頭。

更新於: 30-7-2019

954 人瀏覽

職業生涯開啟

完成課程認證

立即開始
廣告
© . All rights reserved.