[英]swift - How to make Add to Favorites with NSURL array
我正在尝试构建一个应用程序存储用户可以播放的特定声音。 我向你保证我已经搜索了2天,但我找不到我想要的东西。 (或者我不能用那些tuts idk成功)
应用程序商店的声音如下:
var sound1 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "Adios Amigos", ofType: "mp3")!)
var sound2 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "ses2", ofType: "mp3")!)
var sound3 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "ses3", ofType: "mp3")!)
var sound4 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "ses4", ofType: "mp3")!)
var soundArray: [NSURL] = [sound1, sound2, sound3, sound4]
这是我的按钮,播放声音随机:
@IBAction func Rastgele(sender: Any) {
let randNo = Int(arc4random_uniform(UInt32(soundArray.count))) // 0...ArrayCount
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOf: (soundArray[randNo] as NSURL) as URL)
audioPlayer.prepareToPlay()
audioPlayer.play()
self.sesLabel.text = soundArray[randNo].deletingPathExtension?.lastPathComponent
soundIndex = randNo} catch {
print(error)
}
}
这是我的IBAction按钮,我无法填写代码。
@IBAction func Favori(_ sender: Any) {
// empty
}
我试图使用NSUserdefaults,但我无法实现我想要的。 我也试图从我的数组中拉出数组项来插入另一个数组但由于数组类型(NSURL)我遇到了很多问题
因此,'Favori'按钮应存储为收藏夹,然后我可以在其他表视图中显示收藏的声音。
提前致谢。
编辑
我找到了一个使用Core Data并将NSURL转换为URL的解决方案。 感谢@rmaddy的有用评论。 工作代码低于;
@IBAction func Favori(_ sender: Any) {
// save core data
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let newSound = NSEntityDescription.entity(forEntityName: "Sounds", in: context)
let sound = NSManagedObject(entity: newSound!, insertInto: context)
sound.setValue(soundArray[soundIndex].deletingPathExtension().lastPathComponent, forKey: "soundName")
do { try context.save()
soundItems.append(sound)
print(sound)
}
catch
{
print("error")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.