簡體   English   中英

swift - 如何使用NSURL數組添加到收藏夾

[英]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")
        }

    }

單擊該按鈕時,使用sqlite或服務器將URL保存到核心數據本地數據庫中 如果您只想將其傳遞給另一個tableview而不保存它(當您終止應用程序時數據將丟失),您可以使用委托通知中心傳遞它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM