Search code examples
iosswiftnsfilemanager

Why are the audio files I've added to my xcode project available in the simulator but are not available when i deploy the app on iPhone


I am using an AVQueuePlayer to play local audio files which I have added to my Xcode project by dragging and dropping the .mp3 files into my folder in the project navigator pane. I then use this code to search thru my files and extract the files that I want, which I then use to fill a table view and to create AVPlayerItems for to play in my AVQueuePlayer.

My code works fine when I run the app on simulator but when i run the app on my iPhone, an error occurs and returns

fatal error: unexpectedly found nil while unwrapping an Optional value

Here is the code causing the issue...

var songNameArray: Array<String> = [String]()
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath("/Users/UsersName/Desktop/Xcode Projects Folder/LocalAudioFilePlayer/LocalAudioFilePlayer")!

while let element = enumerator.nextObject() as? String {
    if element.hasSuffix("mp3") {
        songNameArray.append(element)
        print(element)
    }
}

Are the files not being properly copied into the bundle which is then deployed to the iPhone? If so, what is the proper way to add the audio files?

I also tried this...

var songNameArray: Array<String> = [String]()
let path = String(NSBundle.mainBundle().resourcePath)
let songFiles = try!      NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)

for item in songFiles {
    if item.hasSuffix("mp3"){
        songNameArray.append(item)
        print("appended to songNameArray \(item)")
    }
}

But I get the error

The folder “LocalAudioFilePlayer.app")” doesn’t exist

Any help is greatly appreciated


Solution

  • let path = String(NSBundle.mainBundle().resourcePath)
    

    This line is not doing what you might think it does. NSBundle.mainBundle().resourcePath returns String?, which is an optional type. When you create a string from that by wrapping String() around it, it doesn't unwrap the optional, it creates a string describing the optional, which looks like this:

    Optional("/Users/markbes/Library/Developer/CoreSimulator/Devices/18D62628-5F8A-4277-9045-C6DE740078CA/data/Containers/Bundle/Application/3DDC064C-0DD1-4BE9-8EA4-C151B65ED1E1/Resources.app")
    

    What you want there is something more like

    var path = NSBundle.mainBundle().resourcePath!
    

    That unwraps the String? type, and gives you a string (or throws an error).