iOS后台下载

iOS后台下载

后台下载是 NSURLSession 带来的一个新特性,区别于以往进入后台只有5分钟完成额外操作

- (void) doUpdate

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        [self beginBackgroundUpdateTask];

        NSURLResponse * response = nil;
        NSError  * error = nil;
        NSData * responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];

        // Do something with the result

        [self endBackgroundUpdateTask];
    });
}

- (void) beginBackgroundUpdateTask
{
//必须的,否则进入后台超时后,APP会被杀掉
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void) endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}   

iOS7以后允许我们,将下载任务交给系统管理,只要 APP 不是被强制用户杀掉,系统会在下载任务完成后,通过特定的函数通知我们。

//生成一个后台session,当然 APP 在前台时,此session 也和普通 session 一样工作。
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("downloadSession")
        self.session = NSURLSession(configuration: config, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {
        print(identifier)
        let _ = TaskManager.sharedInstance
        ch = completionHandler
    }
extension TaskManager: NSURLSessionDownloadDelegate{
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask,
                    didFinishDownloadingToURL location: NSURL) {
        
        print("URLSession(sessionNSURLSessiondownloadTaskNSURLSessionDownloadTask didFinishDownloadingToURL locationNSURL")
        var fileName = ""
        
        for (index, task) in taskList.enumerate() {
            if task.taskIdentifier == downloadTask.taskIdentifier {
                taskList[index].finished = true
                fileName = task.url.lastPathComponent!
            }
        }
        
        if let documentURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first {
            
            let destURL = documentURL.URLByAppendingPathComponent(fileName+"123")
            
            do {
                try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destURL)
            }
            catch {
                print(error)
            }
            saveTaskList()
            NSNotificationCenter.defaultCenter().postNotificationName(DownloadTaskNotification.Finish.rawValue, object: downloadTask.taskIdentifier)
        }
        
    }
    
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
        
        
    }
    
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        
        print("URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)")
        let progressInfo = ["taskIdentifier": downloadTask.taskIdentifier,
                            "totalBytesWritten": NSNumber(longLong: totalBytesWritten),
                            "totalBytesExpectedToWrite": NSNumber(longLong: totalBytesExpectedToWrite)]
        
        NSNotificationCenter.defaultCenter().postNotificationName(DownloadTaskNotification.Progress.rawValue, object: progressInfo)
        
    }
    
    func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
        print("URLSessionDidFinishEventsForBackgroundURLSession")
        (UIApplication.sharedApplication().delegate as! AppDelegate).ch?()
        (UIApplication.sharedApplication().delegate as! AppDelegate).ch = nil
    }
    
}

上述 API 调用顺序如下:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS 后台下载管理工具 XXDownload,通过传入一个url地址就开始下载并且是支持后台下载的,底层是用NS...
    羊子222阅读 6,751评论 12 14
  • iOS的多任务是在iOS4的时候被引入的,在此之前iOS的app都是按下Home键就被干掉了。iOS4虽然引入了后...
    晨曦景雪阅读 4,175评论 1 7
  • 我喜欢和我爸妈大声说话,也喜欢叫我爸妈的名字和各种小外号,也要吵吵架,是吵架不过三分钟就立马破功的那种。经常也看我...
    肖太阳啊阅读 145评论 0 0
  • “岁月是把杀猪刀”的最早出处,我不甚了了;我比较有把握的是,屡见不鲜之际,微微一哂:这年头,怎么会有这么多既黑人又...
    龙潭独步阅读 725评论 0 0
  • 春天是一个多情的季节,当置身于桃之夭夭之中,人不免会有许多的遐想,谁又能抵挡得住这灼灼桃花带来的强烈春的气息...
    yh桦阅读 201评论 0 0