iOS开发 使用NSURLConnection实现下载文件

一.下载小文件

1.第一种方法:直接用Data的contentsOf: URL方法

// 下载小文件(方法1)
class func urlConnectionDownloadSmall(_ url: String, success: @escaping (_ data: Data?) -> Swift.Void, fail: (_ error: Error) -> Swift.Void) {
    if url.isEmpty {
        fail(NSError(domain: "url为空", code: 404, userInfo: [:]))
        return
    }
    do {
        let data = try Data(contentsOf: URL(string: url)!)
        success(data)
    } catch {
        fail(error)
    }
}

2.第二种方法:使用NSURLConnection发送一个HTTP请求去下载

// 下载小文件(方法2)
class func urlConnectionDownloadSmall(_ url: String, success: @escaping (_ data: Data?) -> Swift.Void, fail: @escaping (_ error: Error) -> Swift.Void) {
     if url.isEmpty {
         fail(NSError(domain: "url为空", code: 404, userInfo: [:]))
         return
     }
     let request = URLRequest(url: URL(string: url)!)
     NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) { (response, data, error) in
          if let error = error {
              fail(error)
          } else {
             success(data)
          }
     }
}

3.第三种方法:如果是下载图片,还可以利用SDWebImage框架

二.下载大文件

1.第一种方法:使用NSURLConnectionDataDelegate代理方法

第一步:创建URL和请求

// 下载大文件
func urlConnectionDownload(_ url: String) -> NSURLConnection? {
     let request = URLRequest(url: URL(string: url)!)
     // 发送异步请求
     let connection = NSURLConnection(request: request, delegate: self)
     return connection
}

第二步:设置代理NSURLConnectionDataDelegate

第三步:实现代理NSURLConnectionDataDelegate方法

// 接收到响应头信息的时候就会调用(最先调用的方法),只会调用一次
    func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
        print("didReceive response")
        // 文件的总大小
        totalSize = response.expectedContentLength
        // 得到的文件名称
        fileName = response.suggestedFilename
    }
    
    func connection(_ connection: NSURLConnection, didReceive data: Data) {
        print("didReceive data")
        // 这是拼接数据的方法
        fileData.append(data)
        print(fileData.count / totalSize)
    }
    
    func connectionDidFinishLoading(_ connection: NSURLConnection) {
        print("didFinish loading")
        if let cache = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last {
            let nsCache = cache as NSString
            let fullPath = nsCache.appendingPathComponent(fileName!)
            do {
                 try fileData.write(to: URL(fileURLWithPath: fullPath!))
            } catch {
                 print(error)
            }
            print(fullPath!)
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值