[swift] Swift에서 비디오 재생 시 화면 회전 기능 구현하기

iOS 앱을 개발할 때 비디오를 재생하는 화면이 회전할 수 있도록 만드는 것은 중요한 요소입니다. 이를 정확히 구현하려면 몇가지 추가 사항을 알아야 합니다. 이 글에서는 Swift에서 비디오 재생 중 화면 회전 기능을 구현하는 방법에 대해 알아보겠습니다.

Contents

  1. AVPlayerLayer를 이용한 기본 비디오 재생
  2. 화면 회전을 위한 코드 추가

AVPlayerLayer를 이용한 기본 비디오 재생

먼저, AVKit과 AVFoundation 프레임워크를 import 하고 AVPlayerLayer를 사용하여 기본적인 비디오 재생 기능을 구현합니다.

import AVKit
import AVFoundation

class VideoPlayerViewController: UIViewController {

    var player: AVPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        let videoURL = URL(string: "https://www.example.com/video.mp4")
        player = AVPlayer(url: videoURL!)

        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = view.bounds
        view.layer.addSublayer(playerLayer)

        player?.play()
    }
}

위 코드에서는 AVPlayer를 사용하여 비디오를 재생하고, AVPlayerLayer를 사용하여 비디오를 표시합니다.

화면 회전을 위한 코드 추가

이제 화면을 회전할 때 비디오 재생 화면도 함께 회전하도록 만들어봅시다.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    coordinator.animate(alongsideTransition: { context in
        let orientation = UIDevice.current.orientation
        if orientation.isLandscape {
            playerLayer?.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        } else {
            playerLayer?.frame = CGRect(x: 0, y: 0, width: size.width, height: 300)
        }
    })
}

위 코드에서 viewWillTransition 메서드를 오버라이드하여 디바이스의 회전 이벤트에 대응하여 플레이어 레이어의 크기와 위치를 업데이트합니다.

이제 비디오 재생 화면을 회전할 때 화면도 함께 회전하도록 구현할 수 있습니다.

이러한 방식으로 Swift에서 비디오 재생 화면을 회전하는 기능을 구현할 수 있습니다.