[swift] 스위프트에서 비디오 재생하기

AVPlayer를 사용한 비디오 재생

AVPlayer는 Apple에서 제공하는 비디오 재생을 위한 클래스로, iOS 앱에서 비디오를 재생할 때 주로 사용됩니다. AVPlayer를 사용하여 비디오를 로드하고 재생하는 단계는 다음과 같습니다.

  1. AVPlayer 인스턴스 생성
  2. 비디오 URL 지정
  3. AVPlayerLayer를 사용하여 비디오를 표시할 뷰에 추가
import AVKit
import AVFoundation

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

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

player.play()

위의 코드에서 AVPlayer를 사용하여 비디오를 로드하고, AVPlayerLayer를 사용하여 비디오를 표시할 뷰에 추가하고, play() 메소드를 호출하여 비디오를 재생합니다.

AVPlayerViewController를 사용한 비디오 재생

AVPlayerViewController는 AVPlayer를 사용하여 비디오를 재생하기 위한 편리한 뷰 컨트롤러입니다. AVPlayerViewController를 사용하면 더욱 간편하게 비디오를 재생할 수 있습니다.

import AVKit
import AVFoundation

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

let playerViewController = AVPlayerViewController()
playerViewController.player = player

present(playerViewController, animated: true) {
    player.play()
}

위의 코드에서는 AVPlayerViewController를 생성하여 비디오 URL을 지정하고, present() 메소드를 사용하여 화면에 비디오 재생 화면을 표시하고, 비디오를 재생합니다.

결론

스위프트를 사용하여 iOS 앱에서 비디오를 재생하는 방법에 대해 간단히 살펴보았습니다. AVPlayer를 사용하여 비디오를 컨트롤하거나 AVPlayerViewController를 사용하여 더욱 간단하게 비디오를 재생할 수 있습니다.

더 자세한 내용은 Apple 공식 문서를 참고하세요.