Swift5でカメラアプリを作りたい初心者
解決したいこと
Swiftでカメラアプリを作ろうとしています。
実機テストを行ったところ、カメラが動いている様子はあるのですが画面にカメラ画像が写りませんでした。
解決方法を教えていただけると嬉しいです。
発生している問題・エラー
特にエラーは出ていないのですが、画像の表示がうまくいきません。。。
該当するソースコード
import UIKit
import AVFoundation
class ViewController: UIViewController {
let captureSession = AVCaptureSession()
var captureDevice: AVCaptureDevice?
var previewLayer: AVCaptureVideoPreviewLayer?
let backgroundQueue = DispatchQueue.global()
override func viewDidLoad() {
super.viewDidLoad()
// カメラの設定
setupCamera()
// 画像出力の設定
setupPreviewLayer()
// バックグラウンドでの実行
backgroundQueue.async {
self.startRunningCaptureSession()
// デバッグ部分
if self.captureSession.isRunning {
print("runnnig")
} else {
print("not run")
}
//デバッグ部分
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer?.frame = view.layer.bounds
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
stopRunningCaptureSession()
}
}
// メソッドの中身
extension ViewController {
func setupCamera() {
//Sessionに追加するメディアの品質を指定
captureSession.sessionPreset = .photo
//deviceの指定
let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: AVCaptureDevice.Position.back)
let devices = deviceDiscoverySession.devices
for device in devices {
if device.position == .back {
captureDevice = device
//デバッグ部分
print("find camera")
print(device)
//デバッグ部分
break
} else {
print("device discovery error")
continue
}
}
//Inputの定義
let deviceInput: AVCaptureDeviceInput
do {
deviceInput = try AVCaptureDeviceInput(device: captureDevice!)
//デバッグ部分
print("device can be set")
print(deviceInput)
//デバッグ部分
if captureSession.canAddInput(deviceInput) {
captureSession.addInput(deviceInput)
//デバッグ部分
print("device can be input")
print(captureSession.inputs)
//デバッグ部分
} else {
print("addInput error")
return
}
} catch {
print("deviceInput error")
return
}
}
//カメラの画像の出力
func setupPreviewLayer() {
// 1. previewLayerにcaptureSesionを追加
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
// 2. 画面
previewLayer?.videoGravity = .resizeAspectFill
previewLayer?.frame = view.layer.bounds
// デバッグ部分
print("Session in previewLayer: \(String(describing: previewLayer?.session))") //ここまで大丈夫そう
// デバッグ部分
// 3. Viewへの追加
view.layer.addSublayer(previewLayer!)
}
// カメラ開始
func startRunningCaptureSession() {
captureSession.startRunning()
}
// カメラ停止
func stopRunningCaptureSession() {
captureSession.stopRunning()
// プレビューレイヤーをビューの階層から取り除く
previewLayer?.removeFromSuperlayer()
// プレビューレイヤーを解放する
previewLayer = nil
}
}
該当するソースコード2
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = ViewController()
print("ok")
return true
}
//アプリがアクティブになった時に呼ばれるメソッド
func applicationDidBecomeActive(_ application: UIApplication) {
AVCaptureDevice.requestAccess(for: .video) { granted in
if !granted {
// カメラの使用が許可されなかった場合に処理を行う
// 例: ユーザーにメッセージを表示して、カメラ機能を制限するなど
print("カメラの使用が許可されませんでした。")
}
}
}
}
自分で試したこと
- setupCamera()とsetupPreviewLayer()で設定を完了した後に、captureSession.startRunning()をバックグランドスレッドにて実行させました。
- infoにCamera Usage DescriptionとPhoto Library Usage Descriptionを追加しました。
初心者質問で申し訳ないです。。。
0 likes