Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a file to the main bundle's /Library/Sounds directory?

According to Apple's documentation, sound file in the ~/Library/Sounds will be search by system when trying to play a sound. How do I add a sound file to this folder?

I tried to write to the folder in runtime, but has no permission. I added a Library/Sounds folder in xcode but it doesn't seems to copy over.

enter image description here

xcode -> window -> devices, select my app and show container, folder is not there enter image description here

To add some context, I am doing custom sound for parse push notification. The server guy told me that when broadcasting to many users, sending a custom sound string in the payload for each user will be too difficult. As a work around, I am trying to use a single sound file that will be dynamically overwritten each time the user selects a new sound.

Thus the sound file need to be auto detected by the system and can be modified at run time by the app. Adding the file to the main bundle will not work as it is read only. I am hoping that a file in ~/Library/Sound will be editable.

I have no idea how to proceed at this point. Any help will be greatly appreciated.

Update: I incorrectly tried to create a directory at run time by using

        try fileManager.createDirectoryAtPath("Library/Sounds", withIntermediateDirectories: true, attributes: nil)

The correct code should be

        let libraryDir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true)
        let directoryPath = "\(libraryDir.first!)/Sounds"
        try fileManager.createDirectoryAtPath(directoryPath, withIntermediateDirectories: true, attributes: nil)

My solution to the custom sound problem.

like image 871
Cymric Avatar asked Feb 15 '16 21:02

Cymric


2 Answers

I struggled with this as well. You have to create the Library/Sounds directory programmatically and move your custom sound into it.

let soundsDirectoryURL = fileManager.urls(for: .libraryDirectory, in: .userDomainMask).first!.appendingPathComponent("Sounds")

//attempt to create the folder
do {
    try fileManager.createDirectory(atPath: soundsDirectoryURL.path,
                                    withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
    print("Error: \(error.localizedDescription)")
}
like image 92
RMoore Avatar answered Nov 20 '22 14:11

RMoore


the link you have is for Mac! the correct document for iOS should be here

in summary, you can just add the sound file to your project as a nonlocalized resource of the app bundle.

like image 32
Allen Avatar answered Nov 20 '22 15:11

Allen