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)
import UIKit
 
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
     
    var window: UIWindow?
     
    func application (application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)-> Bool {
            // Enable notification
            let settings = UIUserNotificationSettings (forTypes: [.Alert, .Badge, .Sound],
                categories: nil)
            application.registerUserNotificationSettings (settings)
            return true
    }
     
    func applicationWillResignActive (application: UIApplication) {
    }
     
    func applicationDidEnterBackground (application: UIApplication) {
        // Although the minimum time for background acquisition is defined, iOS will wake up the program by its own best time, which we cannot control
        // UIApplicationBackgroundFetchIntervalMinimum calls our Fetch method as often as possible
        application.setMinimumBackgroundFetchInterval (UIApplicationBackgroundFetchIntervalMinimum)
    }
     
    func applicationWillEnterForeground (application: UIApplication) {
    }
     
    func applicationDidBecomeActive (application: UIApplication) {
    }
     
    func applicationWillTerminate (application: UIApplication) {
    }
     
    // Get data in the background
    func application (application: UIApplication,
        performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult)-> Void) {
            // Create NSURL object
            let url: NSURL! = NSURL (string: "http://api.k780.com:88/?app=life.time&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json")
            // Create a request object
            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)
                         
                        // Let the OS know that fetching data failed
                        completionHandler (UIBackgroundFetchResult.Failed)
                    } else {
                        let str = NSString (data: data !, encoding: NSUTF8StringEncoding)
                        print (str)
                        // Clear all local pushes
                        //UIApplication.sharedApplication (). CancelAllLocalNotifications ()
                        // Create UILocalNotification for local message notification
                        let localNotification = UILocalNotification ()
                        // Push time (immediate push)
                        localNotification.fireDate = NSDate (timeIntervalSinceNow: 0)
                        //Time zone
                        localNotification.timeZone = NSTimeZone.defaultTimeZone ()
                        // Push content
                        localNotification.alertBody = "Success in getting time: \ (str)"
                        //sound
                        localNotification.soundName = UILocalNotificationDefaultSoundName
                        UIApplication.sharedApplication (). ScheduleLocalNotification (localNotification)
                         
                        // Let the OS know that new data has been obtained
                        completionHandler (UIBackgroundFetchResult.NewData)
                        //completionHandler(UIBackgroundFetchResult.NoData)
                    }
            }) as NSURLSessionTask
             
            // Use the resume method to start the task
            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

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.