How to run iOS app in background forever?

Viewed 2500

I am making an iOS application for myself only. I need to execute certain code every 30 minutes when application is in background.

As I am only user of this app, don’t need to worry about batter percentage and apple review process. I can use any/all background modes VOIP, music, etc.

Is is possible to run that code in background every 30 minutes? Kindly guide me the direction.

2 Answers

Its posible.

One way to do it is to create a fake VPN packet tunnel extension. And put your code in VPN Manager class. VPN extension part will keep running while your app is in background or even force quite by user.

You can write your code in this method

NEPacketTunnelProvider

override func startTunnelWithOptions(options: [String : NSObject]?, completionHandler: (NSError?) -> Void) {

          fetchData()
}

func fetchData() {
        // Do not use the NSTimer here that will not run in background
        let q_background = DispatchQueue.global(qos: .background)
        let delayInSeconds: Double = 300.0 // seconds
        let popTime = DispatchTime.now() +  DispatchTimeInterval.seconds(Int(delayInSeconds))
        q_background.asyncAfter(deadline: popTime) {
        // Fetch your data from server and generate local notification by using UserNotifications framework 
            fetchData()
        }
    }

Why not go with Background Fetch?

It is available for apps likes News or Social media, so that apps can have the latest data even before the user interaction. It allows periodic background execution as is.

A simple call will fetch data every hour.

// Fetch data once an hour.
   UIApplication.shared.setMinimumBackgroundFetchInterval(3600)

Lastly its not a workaround or any private API. Your app will be accepted by appstore as well.

Related