How do I use background tasks with Swift 3?

I am new to background tasks. I have a little job where I receive tweets and if my app is in the background then it should also receive tweets, but I don't know how.

I just use Timer in Appdelegate's didFinishLaunchOption method. When I close the application, it won't work. I'm new to this, so any suggestion please. Below is my code:

Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(getTweets), userInfo: nil, repeats: true). 

func getTweets() {

    let locationName = Helper.sharedInstance.userDefault.value(forKey: ModelKey.currentLocation) as? String

    let accessToken = Helper.sharedInstance.userDefault.value(forKey: ModelKey.twitterAccessToken) as? String

    if (locationName == "Bengaluru" && nil != accessToken) || (locationName == "Bangalore" && nil != accessToken){
        tweetModel.getTweets(accessToken: accessToken!, city: ModelKey.blrcitytraffic, cityName: "Bengaluru")
    }
}

      

There is also text to speech, but when I close the application, it stops speaking. If I am not using the app, then it can also receive tweets, and the text-to-speech needs to run in the background. How long does it work?

+3


source to share


2 answers


Background task means that you need to use background threads. There is too much thread in iOS, but if you only want to do a background job, you must use two threads; main and background thread, that's their structure:

DispatchQueue.global(qos: .background).async {
    //background code
    DispatchQueue.main.async {
        //your main thread
    }    
}

      



So, you first initialize the global queue in the background. This thread can be used for a background task, and then you have to use the main thread (only if you want) to do something when the background task is finished. This could be an option. Another option is to be applicationDidEnterBackground

in appDelegate and you can only put your code in that method.

+4


source


You need to do three things:

  • In your Info.plist add the following entry for the key Required background modes

    to allow background network access:

    Required background modes:

    App downloads content from the network

  • In your AppDelegate add your applicationDidEnterBackground ():

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Fetch no sooner than every (60) seconds which is thrillingly short actually. 
        // Defaults to Infinite if not set. 
        UIApplication.shared.setMinimumBackgroundFetchInterval( 60 ) )
    }
    
          

  • Also in the AppDelegate app

    func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
      var fetchResult: UIBackgroundFetchResult!
    
    
      if doingYourStuffActuallyCreatesNetworkTraffic() {
        fetchResult = UIBackgroundFetchResult.newData
      } else if thereWasAnError() { 
        fetchResult = UIBackgroundFetchResult.failed
      } else {
        fetchResult = UIBackgroundFetchResult.noData
      }           
      completionHandler( fetchResult )
    
      return    
    }
    
          

There are still some pitfalls, for example. there is no guaranteed maximum sampling interval and background execution can be significantly different in Xcode / Simulator than on real devices.



You can take a look at this pretty cute topic:

execute the FetchWithCompletionHandler never fired

and of course https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

+3


source







All Articles