我刚学了一门Swift 2.0
课程。我正在尝试创建一个应用程序,从iOS的音乐应用程序库中选择一首歌并播放它。我遇到了这个link,它展示了如何制作媒体项目选择器。
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
行显示
无法指定类型的值' ViewController'输入 ' MPMediaPickerControllerDelegate'?
错误消息。当我阻止它时,该应用程序工作,并允许我完美地浏览歌曲。
问题1:我想知道这条线的用途是什么?
问题2:如何使用此代码播放我选择的歌曲?
我在这里和其他网站搜索了如何播放歌曲。我发现人们正在使用
player.play()
播放音乐。我尝试过但失败了。
答案 0 :(得分:5)
ViewController需要符合' 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: {})
}
添加这些方法以符合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")
}
的目的
'mediaPicker.delegate = self'
是设置ViewController以响应上面添加的功能。如果你没有设置代理,mediaPicker仍会出现,但你的ViewController不知道用户做了一个动作。
每当设置委托时,请确保该类符合委托方法。如果您不了解这些方法,请通过Apple的开发人员文档搜索该代表(即搜索' MPMediaPickerControllerDelegate'),您将看到可以添加的所有委托方法。