Implementation of Swift-background fetch data (Background fetch)

Source: Internet
Author: User

Here's how to get a program to request a background short run. But this extra time is limited after all. So, from IOS7, there are two ways to run tasks in the background: background fetching and background notifications.


1, backstage get introductionBackground access (Background Fetch) is designed for applications that require regular updates, such as weather applications, news clients, social networking applications, and so on. After the background acquisition is started, the application can be woken up in the background, getting the latest information in the background so that the information can be displayed immediately when the user moves the application to the foreground.
2, background access function openFirst in the selected item, in thecapabilities (features) tab, enable Background fetch in Background Modes (background mode) (background acquisition)

3, background get time interval settings(1) After the background acquisition function is turned on, you also need to use it in your code.the Setminimumbackgroundfetchinterval () method sets the time interval (in seconds) for the shortest wake-up program. But when the program will be awakened to get data, it is not controllable. This is decided by the system itself. (2) If you want to tell the call as frequently as possible, set it directly toUiapplicationbackgroundfetchintervalminimum.
4, using the sampleAfter the program is suspended, the Beijing time is automatically retrieved from the background, and a local notification is used to alert the user. (Note: To call Completionhandler after the background fetch executes to tell the system whether the data was successful)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 6667686970717273747576777879 import UIKit@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate {        var window: UIWindow?        func application(application: UIApplication,        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {            //开启通知            let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound],                categories: nil)            application.registerUserNotificationSettings(settings)            return true    }        func applicationWillResignActive(application: UIApplication) {    }        func applicationDidEnterBackground(application: UIApplication) {        //虽然定义了后台获取的最短时间,但iOS会自行以它认定的最佳时间来唤醒程序,这个我们无法控制        //UIApplicationBackgroundFetchIntervalMinimum 尽可能频繁的调用我们的Fetch方法        application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)    }        func applicationWillEnterForeground(application: UIApplication) {    }        func applicationDidBecomeActive(application: UIApplication) {    }        func applicationWillTerminate(application: UIApplication) {    }        //后台获取数据    func application(application: UIApplication,        performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {            //创建NSURL对象            let url:NSURL! = NSURL(string:"http://api.k780.com:88/?app=life.time&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json")            //创建请求对象            let request:NSURLRequest = NSURLRequest(URL: url)                        let session = NSURLSession.sharedSession()                        let dataTask = session.dataTaskWithRequest(request,                completionHandler: {(data, response, error) -> Void in                    if error != nil{                        print(error?.code)                        print(error?.description)                                                //让OS知道获取数据失败                        completionHandler(UIBackgroundFetchResult.Failed)                    }else{                        let str = NSString(data: data!, encoding: NSUTF8StringEncoding)                        print(str)                        //清除所有本地推送                        //UIApplication.sharedApplication().cancelAllLocalNotifications()                        //创建UILocalNotification来进行本地消息通知                        let localNotification = UILocalNotification()                        //推送时间(立刻推送)                        localNotification.fireDate = NSDate(timeIntervalSinceNow: 0)                        //时区                        localNotification.timeZone = NSTimeZone.defaultTimeZone()                        //推送内容                        localNotification.alertBody = "获取时间成功:\(str)"                        //声音                        localNotification.soundName = UILocalNotificationDefaultSoundName                        UIApplication.sharedApplication().scheduleLocalNotification(localNotification)                                                //让OS知道已经获取到新数据                        completionHandler(UIBackgroundFetchResult.NewData)                        //completionHandler(UIBackgroundFetchResult.NoData)                    }            }) as NSURLSessionTask                         //使用resume方法启动任务            dataTask.resume()    }}


5, background get test

(1) Simulator test, as long as the selection of the Xcode menu bar debug under the simulate Background fetch can (2) Real machine debugging, if not attached to the computer sometimes wait a day before the background to get. It may take a few minutes for a computer to be attached. Http://www.hangge.com/blog/cache/detail_815.html

Implementation of Swift-background fetch data (Background fetch)

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.