1, 直接上代码:
//
// JPCDownloadHelper.swift
// BTSDemo
//
// Created by jianxiong li on 16/3/10.
// Copyright © 2016年 joobot. All rights reserved.
//
import Foundation
var helpers:NSMutableDictionary = NSMutableDictionary()
protocol JPCDownloadStatusDelegate{
func bytesReceived(receivedBytes:Int64,totalbytes:Int64,url:String)
func downloadFinishedForFile(url:String,localFileUrl:String)
func downloadResumdForFile(url:String)
func downloadErrorForFile(url:String)
func sessionActive()
}
class JPCDownloadHelper:NSObject,NSURLSessionDelegate,NSURLSessionDownloadDelegate{
var session:NSURLSession?
var resumeDatas:NSMutableDictionary
var delegate:JPCDownloadStatusDelegate?
var backgroundCompletionHandler:(()->())?
class func downloadHelperForIdentifier(identifier:String)->JPCDownloadHelper{
let helper:JPCDownloadHelper? = helpers.objectForKey(identifier) as? JPCDownloadHelper
print("downloadHelperForIdentifier.......helper:\(helper)")
if(helper == nil){
return JPCDownloadHelper(identifier: identifier)
}else{
return helper!
}
}
//便利构造器
// convenience init(){
// self.init(identifier: "com.joobot.ljx.btsdemo")
// }
//指定构造器
private init(identifier:String){
self.resumeDatas = NSMutableDictionary()
super.init()
print("JPCDownloadHelper init.......session:\(session) identifier:\(identifier)")
if(self.session == nil){
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(identifier)
self.session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
helpers.setObject(self, forKey: identifier)
}
}
//激活页面:退出页面,再退出程序后,重新进入页面
// When we connect a UI delegate, the session could be running tasks if app previously crashed. Notify UI delegate asynchronously if so.
class func setDelega(dele:JPCDownloadStatusDelegate,identifier:String){
let helper:JPCDownloadHelper? = helpers.objectForKey(identifier) as? JPCDownloadHelper
print("===============================setDelegate.......helper:\(helper)")
if(helper != nil){
helper?.delegate = dele
// helper?.session?.getTasksWithCompletionHandler({
// dataTasks,uploadTasks,downloadTasks in
// print("=====================