2017-07-19 69 views
3

我是新來的後臺任務。我有一個小工作,我正在獲取推文,如果我的應用程序處於後臺模式,那麼它也應該獲取推文,但我不知道如何。如何使用Swift 3使用後臺任務?

我在的appdelegate 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") 
    } 
} 

文本到語音也有,但是當我關閉應用程序然後停止發言。如果我不使用應用程序,那麼它也可以獲取推文和文本到語音應該使用背景模式工作。這工作多久了?

+1

相關:https://developer.apple.com/library/content/documentation/ iPhone /概念/ iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html –

回答

0

後臺任務意味着你需要使用後臺線程。 iOS中的線程太多了,但是如果你只想做後臺任務,你應該使用兩個線程;主要和後臺線程的結構是:

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

所以,你首先用背景模式初始化全局隊列。這個線程可以用於後臺任務,然後你必須在後臺任務完成時使用主線程(只在你需要的時候)做某件事。這可以是一個選項。在AppDelegate中,另一個選項應該是applicationDidEnterBackground,並且只能將該代碼放入該方法中。

+0

我不知道爲什麼downvotes。這是我來這裏尋找的。 – Suragch

+0

也幫助了我。 +1投票 –

3

你需要做三件事情:

  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)) 
    } 
    
  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  
    } 
    

仍然有一些缺陷,例如沒有保證的最大提取間隔,並且XCode/Simulator中的後臺執行可能與真實設備中的執行有很大不同。

你可以看看這個漂亮的similiar話題:

performFetchWithCompletionHandler never gets fired

,當然還有 https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

相關問題