【问题标题】:Download in background in Swift在 Swift 后台下载
【发布时间】:2015-10-14 18:23:11
【问题描述】:

我正在尝试让我的应用在后台下载图像。但是当我按下 [Home] 按钮时,应用程序停止下载。即使我使用另一个应用程序,有什么方法可以让它继续下载吗?我见过一些应用程序可以这样做,但我不知道如何。

这是我迄今为止尝试过的。

//
//  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)
            }
        })
    })

}

}

回答

根据下面的评论,我找到了这个帖子:objective c - Proper use of beginBackgroundTaskWithExpirationHandler。我可以用它解决我的问题。

【问题讨论】:

    标签: iphone swift download


    【解决方案1】:

    对于图像的下载和存储,我建议你使用一些知名的库,而不是自己编写逻辑,例如:

    背后的原因是这些库经过了良好的测试,非常健壮并且主要非常易于用于基本任务。

    现在对于后台下载,有专门设计的beginBackgroundTaskWithExpirationHandler:。当你使用它时,你将有更多的时间来执行你需要的任何事情(在这个限制之后,你的应用程序无论如何都会被终止)。

    您可以编写以下方法:

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

    当你想使用它时,你只需在开始/结束下载调用时简单地开始/结束任务:

    // Start task
    let task = self.beginBackgroundTask()
    
    // Do whatever you need
    self.someBackgroundTask()
    
    // End task
    self.endBackgroundTask(task)
    

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      使用beginBackgroundTaskWithExpirationHandler:在应用进入后台时从UIApplication启动一个后台任务 有关详细信息,请参阅 Apple 关于多任务后台执行的文档。请参阅download in background in iphone 这是一个类似的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-21
        • 1970-01-01
        • 2023-04-06
        相关资源
        最近更新 更多