3

I'm trying to make my app download images in background. But when I press [Home] button, the app stop download. Is there any way to make it continue download even when I use another app? I have seen some apps can do like that but I don't know how.

This is what I've 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 with it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user38931
  • 471
  • 1
  • 6
  • 16

2 Answers2

3

For downloading and storing of the images, instead of writing the logic yourself, I suggest you use some well known libraries, like:

Reason behind that is those libraries are well tested, quite robust and mainly very easy to use for basic tasks.

Now for the background download, there is beginBackgroundTaskWithExpirationHandler: that is specifically designed to do that. When you use it, you will get few more minutes to execute whatever you need (after that limit, your application will get terminated no matter what).

You can write 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 simple begin / end the task when starting / finishing the download call:

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

// Do whatever you need
self.someBackgroundTask()

// End task
self.endBackgroundTask(task)

Hope it helps!

Jiri Trecak
  • 5,092
  • 26
  • 37
0

Use beginBackgroundTaskWithExpirationHandler: from the UIApplication to start a background task when the app enters the background See Apple's document on multitasking background execution for details. See download in background in iphone its a similar question.

Community
  • 1
  • 1
DatForis
  • 1,331
  • 12
  • 19