如何使用Swift 3 iOS10为MPMediaPickerControllerDelegate呈现带有视图控制器的音乐库?

时间:2016-09-24 13:25:43

标签: ios swift swift3 presentviewcontroller mpmediapickercontroller

我正在尝试关注使用MPMediaPickerControllerDelegate来呈现音乐选择列表的最新帖子。

可在此URL找到该教程:

http://www.justindoan.com/tutorials/

我正在使用此代码:

import UIKit
import MediaPlayer

class ViewController: UIViewController, MPMediaPickerControllerDelegate  {

    var mediapicker1: MPMediaPickerController!

    override func viewDidLoad() {
        super.viewDidLoad()


        let mediaPicker: MPMediaPickerController = MPMediaPickerController.self(mediaTypes:MPMediaType.music)
        mediaPicker.allowsPickingMultipleItems = false
        mediapicker1 = mediaPicker
        mediaPicker.delegate = self
        self.presentViewController(mediapicker1, animated: true, completion: nil)
        }
}

但是我发现了:

self.presentViewController(mediapicker1, animated: true, completion: nil)

不起作用。不幸的是,Swift 3建议的自动解决方案也不起作用:

self.present(mediapicker1, animated: true, completion: nil)

此外,iOS 10 Beta发行说明见于:

https://www.scribd.com/doc/315770725/IOS-10-Beta-Release-Notes

在18页第10页说,

  

MPMediaPickerController对象可能无法按预期显示。

我花了很多时间自己解决这个问题而没有成功。

有什么建议吗?

3 个答案:

答案 0 :(得分:19)

完成以下步骤:

  1. 将“NSAppleMusicUsageDescription”添加到您的Info.plist以获取隐私权。
  2. 确保您的iPhone中有音乐应用。它不适用于模拟器。

答案 1 :(得分:5)

根据我们对评论的讨论,我最近在最新的应用named playmates中使用了MPMediaPickerController。我正在和你分享工作代码。我写了不言自明的代码。

import MediaPlayer

class viewControllerName: UIViewController,MPMediaPickerControllerDelegate {

//Below is Inaction for picking music from media library
    @IBAction func btnMediaPickerAction(_ sender: UIButton) {        
            let mediaPicker: MPMediaPickerController = MPMediaPickerController.self(mediaTypes:MPMediaType.music)
            mediaPicker.delegate = self
            mediaPicker.allowsPickingMultipleItems = false
            self.present(mediaPicker, animated: true, completion: nil)
        }

// MPMediaPickerController Delegate methods
    func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) {
            self.dismiss(animated: true, completion: nil)
        }

        func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
            self.dismiss(animated: true, completion: nil)
            print("you picked: \(mediaItemCollection)")//This is the picked media item. 
//  If you allow picking multiple media, then mediaItemCollection.items will return array of picked media items(MPMediaItem)
            }
}

我在下面的代码中找到了相关信息:

  • 使用self.present而非self.presentViewController
  • 无需创建mediaPicker的全局实例。与委托方法一样,您将获得MPMediaPickerController
  • 的实例

答案 2 :(得分:0)

添加隐私-info.plist中的媒体库使用说明