abharku
abharku

Reputation: 145

Swift 3 how to override silent mode and play audio from background

I am trying to write an app which works like phone finder but with completely different usages and channel of invocation. I am able to get user's location and do background fetch alright but the thing I am struggling with is to play sound on loud volume (Even when phone is silent) to find user's phone when they have lost it in the house. It was all easy on Android and I will like to replicate this on iOS as well. I was able to play sound when the app switches from foreground to background by doing this:

func setupAudio(){
        print("Trying to play audio")
        guard let sound = NSDataAsset(name: "FeelinGood") else {
            print("asset not found")
            return
        }


        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)

            audioPlayer = try AVAudioPlayer(data: sound.data, fileTypeHint: AVFileTypeMPEGLayer3)

                audioPlayer.play()


        } catch let error as NSError {
            print("error: \(error.localizedDescription)")
        }


    }

But when I try and invoke the method when I receive a remote notification this doesn't work. I have got alarm to work with my app with remote notification and able to play custom sounds, but that only works when phone is not in silent mode .

There are plenty of apps in app store which is overriding silent mode so I am very sure there is a way to do this but I am not sure how as yet.

Upvotes: 4

Views: 3408

Answers (2)

abharku
abharku

Reputation: 145

Thanks, it's all working now. @zombie to answer your question yes I did enable background mode and Audio as without it I can't get background fetch to work or audio to play when the app goes in the background.

My problem was that I was setting AudioSession twice. Once on Launch and again when I was getting a remote notification. Once I removed it from launch it all started working. Coming from java background I was under an impression that I am simply reinitializing an object. Clearly not. It will be helpful if someone can throw some light on it though.

Upvotes: 1

zombie
zombie

Reputation: 5269

Did you try setting the volume to the player

audioPlayer.volume = 1

also don't forget to enable the background modes

enter image description here

Upvotes: 0

Related Questions