我有两个视图控制器,一个带有mediapicker,另一个带有实际播放器。 所以我完成了这段代码:
第一个视图
import UIKit
import MediaPlayer
class WelcomeView: UIViewController, MPMediaPickerControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
var mediaPicker: MPMediaPickerController = MPMediaPickerController.self(mediaTypes:MPMediaType.Music)
mediaPicker.allowsPickingMultipleItems = false
mediapicker1 = mediaPicker
mediaPicker.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning() }
var mediapicker1 = MPMediaPickerController()
@IBAction func selectsong(sender: AnyObject) {
self.presentViewController(mediapicker1, animated: true, completion: nil)
}
func mediaPicker(mediaPicker: MPMediaPickerController!, didPickMediaItems mediaItemCollection: MPMediaItemCollection!) {
self.dismissViewControllerAnimated(true, completion: nil)
println("you picked: \(mediaItemCollection)")
selectedelement = mediaItemCollection
let vc = MainView(nibName: "MainView", bundle: nil)
navigationController?.pushViewController(vc, animated: true)
}
var selectedelement = MPMediaItemCollection()
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestView: MainView = segue.destinationViewController as MainView
DestView.selectedsong = selectedelement
}}
和播放器视图
import UIKit
import MediaPlayer
class MainView: UIViewController {
var play = MPMusicPlayerController()
var selectedsong = MPMediaItemCollection()
override func viewDidLoad() {
super.viewDidLoad()
func prepareToPlay() -> Bool{
let myplayer = MPMusicPlayerController.applicationMusicPlayer()
myplayer.setQueueWithItemCollection(selectedsong)
play = myplayer
myplayer.play()
return true
}}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}}
但是当我点击开始时,xcode会给我这个错误: “MPMediaItemCollectionInitException”,原因:' - 不支持-init,请使用-initWithItems:“
我在google上搜索了这个,发现了“我实际上没有在后台运行查询”这样的内容
所以我真的不知道该怎么做))
答案 0 :(得分:0)
问题在于您正在初始化变量,而不仅仅是声明它们而且您选择的初始化程序无效。
var selectedsong = MPMediaItemCollection()
// missing "items:" in constructor ^
由于您在selectedsong
中设置了prepareForSegue
,您应该简单地声明它而不是尝试初始化值:
var selectedsong : MPMediaItemCollection
旁注:play
也是如此。在第一次使用它之前,您正在prepareToPlay
重置其值,因此每次都会抛弃此初始值。
var play : MPMusicPlayerController