I'm trying to build an app stores specific sounds which user can play. I assure you I've searched for 2 days but I couldn't what I look for. (Or I couldn't successful with those tuts idk)
The app stores sounds like this:
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]
here is my button that play sounds as random:
@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)
}
}
and here is my IBAction button that I couldn't fill inside with code.
@IBAction func Favori(_ sender: Any) {
// empty
}
I tried to use NSUserdefaults but I couldn't achieve what I want. I also tried to pull the array item from my array to insert another array but I faced many problems with because of type of array(NSURL)
So, 'Favori' button should store as Favorites then I can show favorited sounds in other table view.
Thanks in advance.
EDIT
I found a solution using Core Data and converting NSURLs to URL. Thanks to the @rmaddy for helpful comment. The working code is down below;
@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")
}
}
When you click on the button, save the URL into core data or a local data base using sqlite or a server. If you just want to pass it to another tableview without saving it (data will lost when you kill the app), you can pass that around using a delegate or notification center .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.