By Dennis


2012-05-20 13:55:36 8 Comments

How do I keep my application running in the background? Would I have to jailbreak my iPhone to do this? I just need this app to check something from the internet every set interval and notify when needed, for my own use.

7 comments

@Dima Rostopira 2018-10-01 13:19:08

I found a way, to keep app running in background by playing silence

Make sure, that you selected audio playback in background modes

Also, don't use this method for long time, since it consumes CPU resources and battery juice, but I think it's a suitable way to keep app alive for a few minutes.

Just create an instance of SilencePlayer, call play() and then stop(), when you done

import CoreAudio

public class SilencePlayer {
    private var audioQueue: AudioQueueRef? = nil
    public private(set) var isStarted = false

    public func play() {
        if isStarted { return }
        print("Playing silence")
        let avs = AVAudioSession.sharedInstance()
        try! avs.setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
        try! avs.setActive(true)
        isStarted = true
        var streamFormat = AudioStreamBasicDescription(
            mSampleRate: 16000,
            mFormatID: kAudioFormatLinearPCM,
            mFormatFlags: kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked,
            mBytesPerPacket: 2,
            mFramesPerPacket: 1,
            mBytesPerFrame: 2,
            mChannelsPerFrame: 1,
            mBitsPerChannel: 16,
            mReserved: 0
        )
        let status = AudioQueueNewOutput(
            &streamFormat,
            SilenceQueueOutputCallback,
            nil, nil, nil, 0,
            &audioQueue
        )
        print("OSStatus for silence \(status)")
        var buffers = Array<AudioQueueBufferRef?>.init(repeating: nil, count: 3)
        for i in 0..<3 {
            buffers[i]?.pointee.mAudioDataByteSize = 320
            AudioQueueAllocateBuffer(audioQueue!, 320, &(buffers[i]))
            SilenceQueueOutputCallback(nil, audioQueue!, buffers[i]!)
        }
        let startStatus = AudioQueueStart(audioQueue!, nil)
        print("Start status for silence \(startStatus)")
    }

    public func stop() {
        guard isStarted else { return }
        print("Called stop silence")
        if let aq = audioQueue {
            AudioQueueStop(aq, true)
            audioQueue = nil
        }
        try! AVAudioSession.sharedInstance().setActive(false)
        isStarted = false
    }

}

fileprivate func SilenceQueueOutputCallback(_ userData: UnsafeMutableRawPointer?, _ audioQueueRef: AudioQueueRef, _ bufferRef: AudioQueueBufferRef) -> Void {
    let pointer = bufferRef.pointee.mAudioData
    let length = bufferRef.pointee.mAudioDataByteSize
    memset(pointer, 0, Int(length))
    if AudioQueueEnqueueBuffer(audioQueueRef, bufferRef, 0, nil) != 0 {
        AudioQueueFreeBuffer(audioQueueRef, bufferRef)
    }
}

Tested on iOS 10 and Swift 4

@Yogesh Raut 2019-01-16 09:13:03

Thank you for sharing this.

@Yogesh Raut 2019-01-28 10:58:59

:- How much time silence player plays sound?

@Dima Rostopira 2019-01-28 11:23:34

@YogeshRaut it plays silence until you call stop()

@simonthumper 2019-02-22 13:47:19

@DimaRostopira I'm doing something similar to this but notice my app still gets quit after a few hours. My code does use AVAudioPlayer mind rather than audio queues like yours, how long have you seen this successfully keep your app running for?

@Dima Rostopira 2019-02-22 14:08:59

@simonthumper I'm using this only for 3 minutes, I don't need more than that

@simonthumper 2019-02-22 14:12:31

@DimaRostopira okay fair enough! :)

@Fallstreak 2019-03-29 11:23:54

@DimaRostopira Why did you use so complex code? All examples with silent sound I saw before was contains AVAudioPlayer (numberOfLoops = -1). Is there some kind of trick?

@Dima Rostopira 2019-03-29 11:37:58

@Fallstreak I already had code, that was used to play raw audio using audio queues, so I just adapted it to play silence. No tricks here

@Fallstreak 2019-03-29 14:17:20

@DimaRostopira Did you compare AVAudioPlayer vs audio queues in background? Is there any pros/cons between them? I don't know which one to choose. I've tested AVAudioPlayer (empty sound, infinity loops) and sometimes I had LocalPlayerHandleCallback crashes. Maybe you know much more than I do. I appreciate your help, thank you.

@Dima Rostopira 2019-04-01 09:56:34

@Fallstreak never compared, and I have no idea, sorry

@user523234 2012-05-20 14:44:19

Yes, no need to jailbreak. Check out the "Implementing long-running background tasks" section of this doc from Apple.

From Apple's doc: Declaring Your App’s Supported Background Tasks

Support for some types of background execution must be declared in advance by the app that uses them. An app declares support for a service using its Info.plist file. Add the UIBackgroundModes key to your Info.plist file and set its value to an array containing one or more of the following strings: (see Apple's doc from link mentioned above.)

@takrishna 2014-02-17 13:09:26

Will this method work 24 x 7 - forever ?

@ToolmakerSteve 2016-05-18 23:58:51

@takrishna, If you are writing this app for your own use, then set UIBackgroundModes value "voip" (Voice over IP). That is the easiest type of app to keep alive forever in background. (But don't submit it to app store, unless it really is a VOIP app.)

@ToolmakerSteve 2016-05-19 00:00:37

For an app store app, if you don't have a server to periodically send "Remote notifications" to your phone, your only other option is "Background fetch". stackoverflow.com/a/37311611/199364

@Saad 2012-05-20 14:00:26

Use local notifications to do that. But this will not check every time. You will have to set a time where you will check your specific event, you may shorten this by decreasing your time slot. Read more about local notification to know how to achieve this at:

http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction/Introduction.html

@ToolmakerSteve 2016-05-18 23:53:29

No, if the app is in background, all that a local notification will do is show that notification to the user. You can't do any actual work unless the user clicks on the notification to bring the app to foreground.

@user1988 2012-05-21 11:13:22

Yes you can do something like this. For that you need to set entry in info.plist to tell os that my app will run in background. I have done this while I wanted to pass user's location after particular time stamp to server. For that I have set "Required background modes" set to "App registers for location updates".

You can write a handler of type UIBackgroundTaskIdentifier.

@nycynik 2012-05-20 14:48:31

I know this is not the answer to your question, but I think it is a solution.

This assumes that your trying to check something or get data from the internet on a regular basis?

Create a service that checks the internet every set interval for whatever it is you want to know, and create a push notification to alert you of it, if the server is down, or whatever it is your trying to monitor has changed state. Just an idea.

@Mrunal 2012-05-20 14:00:41

I guess this is what you required

When an iOS application goes to the background, are lengthy tasks paused?

iOS Application Background Downloading

This might help you ...

Enjoy Coding :)

@user1320885 2012-05-20 13:57:02

You can already do this in the applicationDidEnterBackground Method

@Dennis 2012-05-20 13:59:26

I thought the app will automatically be terminated after some duration, will it not? Pardon my ignorance if I'm wrong. I'm very new to iOS programming.

@user1320885 2012-05-20 14:00:38

unless iOS needs that memory for another app, it won't be, and as long as you are doing something in the background

@Greg 2012-05-20 15:25:36

No. Applications cannot run in the background for over 10 minutes, except for a few certain situations (VOIP, playing audio, etc.)

Related Questions

Sponsored Content

42 Answered Questions

[SOLVED] Passing Data between View Controllers

32 Answered Questions

[SOLVED] Can I embed a custom font in an iPhone application?

  • 2008-12-11 20:21:11
  • Airsource Ltd
  • 234746 View
  • 768 Score
  • 32 Answer
  • Tags:   ios cocoa-touch fonts

23 Answered Questions

[SOLVED] Xcode error "Could not find Developer Disk Image"

  • 2015-06-09 15:48:57
  • Nathan Kramer
  • 532625 View
  • 865 Score
  • 23 Answer
  • Tags:   ios iphone xcode

13 Answered Questions

[SOLVED] How do I animate constraint changes?

24 Answered Questions

[SOLVED] How to detect iPhone 5 (widescreen devices)?

14 Answered Questions

[SOLVED] Xcode process launch failed: Security

41 Answered Questions

[SOLVED] How to check for an active Internet connection on iOS or macOS?

15 Answered Questions

8 Answered Questions

[SOLVED] iOS 6 apps - how to deal with iPhone 5 screen size?

  • 2012-09-12 21:40:08
  • jturolla
  • 161025 View
  • 264 Score
  • 8 Answer
  • Tags:   iphone ios iphone-5

10 Answered Questions

[SOLVED] How much does it cost to develop an iPhone application?

Sponsored Content