How do I add a file to the main bundle's /Libr

2019-04-07 10:19发布

问题:

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.

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

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.

回答1:

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.



回答2:

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)")
}


回答3:

I had the exact same problem at work. I would suggest -

  1. Have multiple sound files in your project.
  2. Persist user's sound selection.
  3. When you receive push notification, play the sound using what you persisted in step 2.