IOS开发Swift用NSURLSessionDownloadTask实现后台下载

本文介绍了如何使用Swift的NSURLSessionDownloadTask在iOS设备上实现后台下载任务,包括具体的操作步骤和一个包含Swift代码的demo示例。
摘要由CSDN通过智能技术生成
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("=====================
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值