Picking a song and play from Music app library - Swift 2.0

I just took a basic Swift 2.0 course. I am trying to make an app to select a song from iOS's Music app library and play it. I came across this link which shows how to make media item picker.

import UIKit
import MediaPlayer

class ViewController: UIViewController {

@IBOutlet weak var pickSong: UIButton!

override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view, typically from a nib.

  let mediaPicker = MPMediaPickerController(mediaTypes: .Music)

  // mediaPicker.delegate = self
  // mediaPicker.prompt = "Select song (Icloud songs must be downloaded to use)"
  mediaPicker.allowsPickingMultipleItems = false
  mediaPicker.showsCloudItems = false
  presentViewController(mediaPicker, animated: true, completion: {})
}

mediaPicker.delegate = self line shows

Cannot assign value of type 'ViewController' to type 'MPMediaPickerControllerDelegate?'

error message. When I blocked it, the app works and allow me to browse songs perfectly.

Question 1: I would like to know what is the use of this line?

Question 2: How to play a song that I picked using this code?

I searched here and other websites for how to play songs. I found people are using player.play() to play music. I tried that and failed.

Upvotes: 2

Views: 7364

Answers (1)

pj.self
pj.self

Reputation: 81

ViewController needs to conform to the 'MPMediaPickerControllerDelegate':

//Let other classes know ViewController is a MPMediaPickerControllerDelegate
class ViewController: UIViewController, MPMediaPickerControllerDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let mediaPicker = MPMediaPickerController(mediaTypes: .Music)
    mediaPicker.delegate = self
    presentViewController(mediaPicker, animated: true, completion: {})
 }

Add these methods to conform to MPMediaPickerControllerDelegate:

 func mediaPicker(mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {

    //User selected a/an item(s). 
    for mpMediaItem in mediaItemCollection.items {
      print("Add \(mpMediaItem) to a playlist, prep the player, etc.")
    }
 }

 func mediaPickerDidCancel(mediaPicker: MPMediaPickerController) {
    print("User selected Cancel tell me what to do")
 } 

The purpose of

'mediaPicker.delegate = self' 

is to setup ViewController to respond to the functions added above. If you don't set the delegate the mediaPicker will still present, but your ViewController won't know the user made an action.

Whenever you set a delegate, make sure the class conforms to the delegate methods. If you don't know the methods, search through Apple's Developer docs for that delegate (ie search for 'MPMediaPickerControllerDelegate') and you'll see all the delegate methods you can add.

Upvotes: 8

Related Questions