Download in the background in Swift

I am trying to make my application load images in the background. But when I press the [Home] button, the application stops downloading. Is there any way I can get it to continue downloading even when I'm using another app? I have seen how some applications can do this, but I do not know how to do it.

This is what I have tried so far.

//
//  AppDelegate.swift
//  Swift-TableView-Example
//
//  Created by Bilal ARSLAN on 11/10/14.
//  Copyright (c) 2014 Bilal ARSLAN. All rights reserved.
//

import UIKit
import WebKit

protocol DownloadInBackgroundDelegate {
func downloadInBackgroundDidFinish(chapterid:Int, chaptername:String,    storyid:Int, progressPercent:Float)
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var shareCache = NSURLCache()
var downloadDelegate:DownloadInBackgroundDelegate? = nil

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    var navigationBarAppearace = UINavigationBar.appearance()

    application.setStatusBarOrientation(UIInterfaceOrientation.PortraitUpsideDown, animated: false)

    self.startDownload()

    return true
}

func application(application: UIApplication,
    didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
    fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

}

func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    FBAppEvents.activateApp()
}

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {

}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

}

func applicationDidReceiveMemoryWarning(application: UIApplication) {
    NSURLCache.sharedURLCache().removeAllCachedResponses()
}

func application(application: UIApplication, willChangeStatusBarOrientation newStatusBarOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    application.windows
}

func startDownload(){
    var filesPath = [String]()
    filesPath.append("https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf")
    filesPath.append("https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/MobileHIG.pdf")
    filesPath.append("https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/NetworkingOverview.pdf")
    filesPath.append("https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/AVFoundationPG.pdf")
    filesPath.append("http://manuals.info.apple.com/MANUALS/1000/MA1565/en_US/iphone_user_guide.pdf")

    downloadFiles(0, filesPath: filesPath)
}

func downloadFiles(index: Int, filesPath: [String]) -> Void {
    var imgURL: NSURL = NSURL(string: filesPath[index].stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()).stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!
    let request: NSURLRequest = NSURLRequest(URL: imgURL)
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
        var fileCacheName = String(format: "%04d", index)

        dispatch_async(dispatch_get_main_queue(), {
            var fileExt = (data != nil && error == nil) ? Utility.checkImageType(data) : ""

            let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
            let imagePath = paths.stringByAppendingPathComponent("\(fileCacheName).png")

            if data.writeToFile(imagePath, atomically: false)
            {
                println("saved")
            }

            if index < filesPath.count - 1
            {
                var nextIndex:Int = index + 1
                self.downloadFiles(nextIndex, filesPath: filesPath)
            }
        })
    })

}

}

      

Answer

Based on the comment below, I found this thread: Objective c - Proper use of beginBackgroundTaskWithExpirationHandler . I can solve my problem.

+3


source to share


2 answers


For loading and saving images, instead of writing logic, I suggest you use some well-known libraries, for example:

The reason is that these libraries are well tested, reliable enough, and generally very easy to use for basic tasks.

Now there is a background download beginBackgroundTaskWithExpirationHandler:

specially designed for this. When you use it, you will get a few more minutes to complete whatever you need to do (after this limit, your application will be terminated no matter what).

You can write the following methods:



func beginBackgroundTask() -> UIBackgroundTaskIdentifier {
    return UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({})
}

func endBackgroundTask(taskID: UIBackgroundTaskIdentifier) {
    UIApplication.sharedApplication().endBackgroundTask(taskID)
}

      

When you want to use it, you just start / end the task when the download call starts / ends:

// Start task
let task = self.beginBackgroundTask()

// Do whatever you need
self.someBackgroundTask()

// End task
self.endBackgroundTask(task)

      

Hope it helps!

+2


source


Using beginBackgroundTaskWithExpirationHandler: from UIApplication to start a background task when the app enters the background For details, see Apple doc on Multitasking Backgrounds. See download in background on iphone for its similar question.



0


source







All Articles