如何使用Swift 3使用后台任务? [英] How to use background task using Swift 3?

查看:112
本文介绍了如何使用Swift 3使用后台任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new in background tasks. I have a small work that I am fetching tweets and If my app is in background mode then also it should fetch tweets, but I don't know how.

我在Appdelegate didFinishLaunchOption方法中仅使用Timer.当我关闭应用程序时,它将无法正常工作.我是新来的,所以请提出任何建议.下面是我的代码:

I am using simply Timer in Appdelegate didFinishLaunchOption Method. When I will close the app then it's not working. I am new in that so please any suggestion. Here 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")
    }
}

也有文字转语音功能,但是当我关闭应用程序时,它将停止说话.如果我不使用应用程序,那么它也可以获取推文,并且文本转语音应该可以在后台模式下工作.那能工作多久?

Text to speech is also there but when I will close the app then it stops speaking. If I am not using app then also it can fetch tweets and text to speech should work using a background mode. How long does that work?

推荐答案

后台任务意味着您需要使用后台线程. iOS中的线程太多,但是如果您只想执行后台任务,则应使用两个线程.主线程和后台线程的结构是:

A background task means you need to use background threads. Threads in iOS are too many, but if you want to make only background task, you should use two threads; the main and background thread that their structure is:

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

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

So, you firstly initialize the global queue with background mode. This thread can be used for background task and then you must use main thread (only if you want) for doing something when the background task is finished. This can be an option. Another option should be applicationDidEnterBackground in appDelegate and you can only must put your code in that method.

这篇关于如何使用Swift 3使用后台任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆