如何使用Swift 3使用后台任务?

kis*_*011 7 background background-process ios tweets swift

我是后台任务的新手.我有一个小作品,我正在获取推文,如果我的应用程序是在后台模式,那么它也应该提取推文,但我不知道如何.

我在Appdelegate中使用了简单的Timer didFinishLaunchOption方法.当我关闭应用程序时,它不起作用.我是新手,所以请任何建议.以下是我的代码:

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")
    }
}
Run Code Online (Sandbox Code Playgroud)

文本到语音也在那里但是当我关闭应用程序然后它停止说话.如果我不使用应用程序,那么它也可以获取推文,文本到语音应该使用后台模式.这有多长时间了?

Alf*_*o G 10

后台任务意味着您需要使用后台线程.iOS中的线程太多,但如果你只想做后台任务,你应该使用两个线程; 它们的结构是主线程和后台线程:

DispatchQueue.global(qos: .background).async {
    //background code
    DispatchQueue.main.async {
        //your main thread
    }    
}
Run Code Online (Sandbox Code Playgroud)

因此,您首先使用后台模式初始化全局队列.此线程可用于后台任务,然后您必须使用主线程(仅在您需要时)在后台任务完成时执行某些操作.这可以是一种选择.另一个选项应该是applicationDidEnterBackgroundappDelegate,您只能将代码放在该方法中.


chr*_*gle 10

你需要做三件事:

  1. 在Info.plist中,为密钥添加以下条目Required background modes以允许后台网络访问:

    Required background modes: App downloads content from the network

  2. 在AppDelegate中添加到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 ) )
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 也在AppDelegate中实现

    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    
    }
    
    Run Code Online (Sandbox Code Playgroud)

仍然存在一些缺陷,例如,没有保证的最大获取间隔,并且后台执行在XCode/Simulator中可能与在真实设备上的行为大不相同.

你可以看一下这个非常类似的主题:

performFetchWithCompletionHandler永远不会被触发

当然还有 https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html