SwiftUIでMPMediaPickerController

SwiftUIって何っ。すっかり浦島状態継続。

以下のコード以外に、info.plistに権限要求を定義(追加)する必要があります。Valueはとりあえずは適当な文章で。起動後の権限要求画面で表示されます。

Privacy - Media Library Usage Description
Privacy - Music Usage Description



また、実行は実機上で行う必要があります。Music Picker表示後に何も選ばずにキャンセルするとsetQueueでクラッシュします。

import SwiftUI
import MediaPlayer

struct ContentView: View {
    @State var isPresented: Bool = false
    @State var collection: MPMediaItemCollection?
    var musicPlayer = MPMusicPlayerController.applicationMusicPlayer
    var body: some View {
        VStack(alignment: .center) {
            Button("Select Music"){
                self.isPresented.toggle()
            }.sheet(isPresented: $isPresented, onDismiss: {
                musicPlayer.setQueue(with: self.collection!)
                musicPlayer.prepareToPlay()
                musicPlayer.play()
            }, content: {
                MusicPicker(collection: self.$collection)
            })
        }.padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct MusicPicker: UIViewControllerRepresentable {
    @Environment(\.presentationMode) var presentationMode
    @Binding var collection: MPMediaItemCollection?

    class Coordinator: NSObject, UINavigationControllerDelegate, MPMediaPickerControllerDelegate {
        var parent: MusicPicker
        init(_ parent: MusicPicker) {
            self.parent = parent
        }
        func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
            if (mediaItemCollection.items.count) > 0 {
                parent.collection = mediaItemCollection
                mediaPicker.dismiss(animated: true, completion: nil)
            }
        }
    }
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    func makeUIViewController(context: UIViewControllerRepresentableContext<MusicPicker>) -> MPMediaPickerController {
        let picker = MPMediaPickerController()
        picker.allowsPickingMultipleItems = true
        picker.delegate = context.coordinator
        return picker
    }
    func updateUIViewController(_ uiViewController: MPMediaPickerController, context: UIViewControllerRepresentableContext<MusicPicker>) {
    }
}

理解はこれから・・・。チュートリアルをこなすのが手っ取り早いか。

参照:
MPMediaPickerController in SwiftUI?