본문 바로가기

iOS/Toy project

[iOS : Toy Project] Apple Music App (5) : Player 화면 + 싱글톤

이전 포스팅

- AppleMusicApp(1) : 뷰 구성

- AppleMusicApp(2) : Track 모델 (데이터 구조)

- AppleMusicApp(3) : UiCollectionViewCell 업데이트

- AppleMusicApp(4) : HeaderView (CollectionReusableView)

 

자세한 코드는 여기로!

https://github.com/yexjin/iOS_Study/tree/main/AppleMusicApp

 

GitHub - yexjin/iOS_Study: iOS 토이프로젝트 모음집📱

iOS 토이프로젝트 모음집📱. Contribute to yexjin/iOS_Study development by creating an account on GitHub.

github.com

 

 


9/13 

- Player 화면 구성 완료!

- Player 싱글톤 객체 만들기 완료!

 

Player 화면과 관련된 코드들은 Player 폴더에 모두 집어넣었다!

하나의 스토리보드에 여러개의 뷰 컨트롤러를 넣는 것은 협업과정에서 충돌도 많이 일어난다고 한다..! 따라서 저렇게 분리한것 같다.

 

아무튼 Player 화면의 AutoLayout구성과 ViewController 연결은 음.. 많이 한거같으니 넘어가겠다!

 

 

 

주목해야할 점은 SimplePlayer.swift 파일!

이 파일에는 Player 싱글톤 객체가 들어가 있다.

이 객체는 말그대로 지정된 음악을 재생시키는 객체! 

📌 싱글톤 객체?
- 앱 내에 1개만 존재하며, 필요할 때마다 앱 내 어디든 호출되는 객체
- 앱 내에서 그저 player에서 사용될 item을 교체하기만 하면 되니까 singleton 하나만 있어도 좋다.

 

SimplePlayer.swift

//  SimplePlayer.swift

import AVFoundation

class SimplePlayer {

    // static 키워드를 통해 SimplePlayer는 싱글톤 객체가 된다. -> 앱 내의 여기저기서 사용 가능한 객체가 됨.
    static let shared = SimplePlayer()
    
    private let player = AVPlayer()
    
    var currentTime: Double {
        // TODO: currentTime 구하기
        return player.currentItem?.currentTime().seconds ?? 0
    }
    
    var totalDurationTime: Double {
        // TODO: totalDurationTime 구하기
        // - total 시간
        return player.currentItem?.duration.seconds ?? 0
    }

    var isPlaying: Bool {
        // TODO: isPlaying 구하기
        // - 재생 중인가?
        
        // isPlaying은 Extension+AVPlayerItem.swift 파일에서 compute property를 extension 했음.
        return player.isPlaying
    }
    
    var currentItem: AVPlayerItem? {
        // TODO: currentItem 구하기
        // - 현재 재생중인 아이템
        return player.currentItem
    }
    
    init() { }
    
    func pause() {
        // TODO: pause구현
        player.pause()
    }
    
    func play() {
        // TODO: play구현
        player.play()
        
    }
    
    func seek(to time:CMTime) {
        // TODO: seek구현
        // - 원하는 시간재생 (by 슬라이더 바)
        player.seek(to: time)
    }
    
    func replaceCurrentItem(with item: AVPlayerItem?) {
        // TODO: replace current item 구현
        // - AVPlayer에서 재생할 곡 선택(바꾸기)
        player.replaceCurrentItem(with: item)
    }
    
    func addPeriodicTimeObserver(forInterval: CMTime, queue: DispatchQueue?, using: @escaping (CMTime) -> Void) {
        player.addPeriodicTimeObserver(forInterval: forInterval, queue: queue, using: using)
    }
    
}

 

 

저기서 isPlaying 코드는 

// Extension+AVPlayerItem.swift

extension AVPlayer {
    var isPlaying: Bool {
        guard self.currentItem != nil else { return false }
        return self.rate != 0
    }
}

 

 

 


 

이제 Player 화면 이동.. Player 화면에서 동작해야하는 기능들.. 아직 많이 남았닥.. 화이팅!