如何在 swift 3 上使用 MPMediaPickerController?
Posted
技术标签:
【中文标题】如何在 swift 3 上使用 MPMediaPickerController?【英文标题】:How to use MPMedaPickerController on swift 3? 【发布时间】:2017-02-12 16:26:27 【问题描述】:我只是想得到它,以便当您按下按钮时,您会显示用户的音乐库,然后您可以选择一首歌曲。我发现做到这一点的方法是通过MPMediaPickerController
,但我一直在努力让它发挥作用。这是我的程序到目前为止的样子:
import MediaPlayer
import UIKit
class ViewController: UIViewController, MPMediaPickerControllerDelegate
var mediaPicker: MPMediaPickerController?
override func viewDidLoad()
super.viewDidLoad()
@IBAction func showSongs(_ sender: Any)
displayMediaPicker()
func displayMediaPicker()
mediaPicker = MPMediaPickerController(mediaTypes: .music)
if let picker = mediaPicker
picker.delegate = self
picker.allowsPickingMultipleItems = false
picker.showsCloudItems = false
picker.prompt = "Please Pick a Song"
view.addSubview(picker.view)
我知道view.addSubview(picker.view)
之后应该有一个属性[self presentViewController:picker animated: true completion:nil]
,但是当我输入它时,我有presentingViewController
和presentedViewContoller
选项,但没有presentViewController
任何帮助将不胜感激
【问题讨论】:
【参考方案1】:函数 presentViewController: animated: completion:
函数在 Swift 3 中被重命名,所以现在看起来像这样:
present(viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?)
所以,在你的情况下,你最终会得到一个看起来像这样的 presentPicker
函数(注意最后一行):
func presentPicker()
mediaPicker = MPMediaPickerController(mediaTypes: .music)
if let picker = mediaPicker
picker.delegate = self
picker.allowsPickingMultipleItems = false
picker.showsCloudItems = false
picker.prompt = "Please Pick a Song"
present(picker, animated: false, completion: nil)
希望对你有所帮助。
【讨论】:
【参考方案2】:Swift 5、Swift 4 非常简单的解决方案
//MARK:- add it in your info.plist file
<key>NSAppleMusicUsageDescription</key>
<string>$(app Name) uses music</string>
//MARK:- Import in your file
import MediaPlayer
//MARK:- Import as your Delegates
MPMediaPickerControllerDelegate
//MARK:- Just call this function
func openAudio()
let audiopicker = MPMediaPickerController(mediaTypes: .anyAudio)
audiopicker.prompt = "Audio"
audiopicker.delegate = self
audiopicker.allowsPickingMultipleItems = false
self.present(audiopicker, animated: true, completion: nil)
【讨论】:
以上是关于如何在 swift 3 上使用 MPMediaPickerController?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Alamofire 请求 swift 3 上发出警报
如何修复 Xcode 7.3 警告:`init` 已弃用:它将在 Swift 3 中删除:在序列上使用`enumerate()` 方法 [重复]