Search code examples
iosswiftavaudioplayersandbox

how to access a sound file stored in another app in swift?


this question is a lot like Share data between two or more iPhone applications except:

  • I'm looking for a way to do this in an iOS 8+ (or 9+) application using swift
  • I want to be able to use the sound file contained in the first app so the easter egg I'm making is only available when the user has both apps installed
  • since this is part of an easter egg, i don't want to use any method that would cause anything extra to be displayed on screen such as a browser redirect or some kind of permission popup

(this basically rules out using the share sheet and custom url's to pass data as described in the post above)

I am using AVAudioPlayer and AVAudioSession in the first app to play the sound if that is at all helpful.


Solution

  • Use App Group

    You can share actual NSData through the NSUserDefaults:

    if let userDefaults = NSUserDefaults(suiteName: <group>) {
        userDefaults.setObject(obj, forKey: key)
    }
    

    and retrieve from another app in the same group like so:

    if let userDefaults = NSUserDefaults(suiteName: <group>) {
        if let obj = userDefaults.objectForKey(key)  {
            // magic
        }
    }
    

    It appears that the only limitation for passing data through the user defaults is the device storage capacity, and since NSUserDefaults accepts NSData as a storage format, it makes a prime candidate for sharing tidbits information.