網站首頁 編程語言 正文
本文實例為大家分享了iOS使用NSURLConnection實現斷點續傳下載的具體代碼,供大家參考,具體內容如下
一.斷點續傳的原理
斷點續傳的原理:每次在想服務器請求下載數據的同時,要告訴服務器從整個下載文件的數據流的某個還未下載的位置開始下載,然后服務器就返回從哪個位置開始的數據流
二.斷點續傳的實現
第一步:先聲明一些屬性
fileprivate var totalSize: Int64 = 0 ? // 總大小
fileprivate var currentSize: Int64 = 0 // 當前大小
fileprivate var fileName: String? ? ? ?// 文件名
fileprivate var fullPath: String? ? ? ?// 文件路勁
fileprivate var handle: FileHandle? ? ?// 句柄
fileprivate var connection: NSURLConnection?
第二步:創建URL和請求
關鍵是設置請求頭
// 下載文件
func urlConnectionDownload(_ url: String) -> NSURLConnection? {
? ? ? ? var request = URLRequest(url: URL(string: url)!)
? ? ? ? // 設置請求頭信息
? ? ? ? /*
? ? ? ? ?bytes=0-1000 表示下載0-1000的數據
? ? ? ? ?bytes=0- ? ? 表示從0開始下載直到下載完畢
? ? ? ? ?bytes=100- ? 表示從100開始下載直到下載完畢
? ? ? ? ?*/
? ? ? ? request.setValue("bytes=\(currentSize)", forHTTPHeaderField: "Range")
? ? ? ? // 發送異步請求
? ? ? ? connection = NSURLConnection(request: request, delegate: self)
? ? ? ? return connection
? ? }
? ? // 取消下載文件
? ? func urlConnectionCacel() {
? ? ? ? connection?.cancel()
? ? }
第三步:設置代理NSURLConnectionDataDelegate
第四步:實現代理NSURLConnectionDataDelegate方法
// 接收到響應頭信息的時候就會調用(最先調用的方法),只會調用一次
? ? func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
? ? ? ? print("didReceive response")
? ? ? ? // 判斷是否已經下載過了
? ? ? ? if currentSize > 0 {
? ? ? ? ? ? // 已經下載過的話,就不需要再次接受response了
? ? ? ? ? ? return
? ? ? ? }
? ? ? ? // 文件的總大小
? ? ? ? totalSize = response.expectedContentLength
? ? ? ? // 得到的文件名稱
? ? ? ? fileName = response.suggestedFilename
? ? ? ? // 邊接收數據邊寫文件到沙盒中
? ? ? ? // 1. 獲取文件的全路徑
? ? ? ? if let cache = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last {
? ? ? ? ? ? let nsCache = cache as NSString
? ? ? ? ? ? fullPath = nsCache.appendingPathComponent(fileName!)
? ? ? ? ? ? // 創建一個空的文件
? ? ? ? ? ? FileManager.default.createFile(atPath: fullPath!, contents: nil, attributes: nil)
? ? ? ? ? ? // 創建句柄
? ? ? ? ? ? handle = FileHandle(forWritingAtPath: fullPath!)
? ? ? ? }
? ? }
? ??
? ? func connection(_ connection: NSURLConnection, didReceive data: Data) {
? ? ? ? print("didReceive data")
? ? ? ? // 把文件句柄移動到文件的末尾
? ? ? ? handle?.seekToEndOfFile()
? ? ? ? // 使用文件句柄寫數據
? ? ? ? handle?.write(data)
? ? ? ? currentSize += data.count
? ? ? ? print(currentSize / totalSize)
? ? }
? ??
? ? func connectionDidFinishLoading(_ connection: NSURLConnection) {
? ? ? ? print("didFinish loading")
? ? ? ? print(fullPath!)
? ? ? ? handle?.closeFile()
? ? ? ? handle = nil
? ? }
原文鏈接:https://blog.csdn.net/wgl_happy/article/details/75610272
相關推薦
- 2022-06-26 Android界面一鍵變灰開發深色適配模式編程示例_Android
- 2022-04-25 C#使用NPOI設置Excel下拉選項_C#教程
- 2022-05-25 <C++>深淺拷貝與初始化列表技巧你真的會了嗎
- 2022-06-14 Python?torch.fft.rfft()函數用法示例代碼_python
- 2022-12-25 python字典中items()函數用法實例_python
- 2023-03-04 Go語言實現分布式鎖_Golang
- 2022-05-21 C語言實現會員管理系統_C 語言
- 2022-06-27 python?使用ctypes調用C/C++?dll詳情_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支