ResumeFromBreakPoint
Swift實現(xiàn)斷點續(xù)傳,Demo簡單易懂,沒有太多復雜模塊和邏輯,完整體現(xiàn)斷點續(xù)傳的原理
對應的Objective-C斷點續(xù)傳:https://github.com/whde/BreakPoint
GitHub:https://github.com/whde/ResumeFromBreakPoint
/*Objective-C*/
pod 'BreakPoint', '~> 1.0.1'
WhdeBreakPoint
簡單的網(wǎng)絡請求隊列管理類,簡單的管理,不做太多復雜處理
/*創(chuàng)建請求,添加請求到數(shù)組中
WhdeSession請求失敗,取消請求等需要從數(shù)組中移除*/
static func asynDownload(urlStr:NSString, progress:ProgressBlock, success:SuccessBlock, failure:FailureBlock) ->WhdeSession
/*取消請求,移除數(shù)組中對應的請求*/
static func cancel(urlStr:String)
/*暫停,即為取消請求*/
static func pause(urlStr:String)
WhdeFileManager
斷點續(xù)傳專用的文件管理
/*根據(jù)NSURL獲取存儲的路徑,文件不一定存在
文件名為Url base64轉換*/
static func filePath(url:NSURL) -> String
/*獲取對應文件的大小*/
static func fileSize(url:NSURL) -> UInt64
/*根據(jù)url刪除對應的文件*/
static func deleteFile(url:NSURL) ->Bool
WhdeSession
網(wǎng)絡收發(fā)
/*創(chuàng)建請求,開始下載,設置已經(jīng)下載的位置*/
func asynDownload(urlStr:NSString, progress:ProgressBlock, success:SuccessBlock, failure:FailureBlock, callCancel:CallCancel) ->WhdeSession
/*取消下載*/
func cancel() -> Void
/*暫停下載即為取消下載*/
func pause() -> Void
/*出現(xiàn)錯誤,取消請求,通知失敗*/
internal func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?)
/*下載完成*/
internal func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
/*接收到數(shù)據(jù),將數(shù)據(jù)存儲*/
internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
let response:NSHTTPURLResponse = dataTask.response as! NSHTTPURLResponse
if response.statusCode == 200 {
/*無斷點續(xù)傳時候,一直走200*/
self.progressBlock!(progress:(Float.init(dataTask.countOfBytesReceived)/Float.init(dataTask.countOfBytesExpectedToReceive)), receiveByte: dataTask.countOfBytesReceived, allByte: dataTask.countOfBytesExpectedToReceive)
self.save(data)
} else if response.statusCode == 206 {
/*斷點續(xù)傳后,一直走206*/
self.progressBlock!(progress:((Float.init(dataTask.countOfBytesReceived+Int64.init(startFileSize))/Float.init(dataTask.countOfBytesExpectedToReceive+Int64.init(startFileSize)))), receiveByte: dataTask.countOfBytesReceived, allByte: dataTask.countOfBytesExpectedToReceive);
self.save(data)
}
}
/*存儲數(shù)據(jù),將offset標到文件末尾,在末尾寫入數(shù)據(jù),最后關閉文件*/
func save(data:NSData) -> Void
使用
var urlStr: String?="http://dlsw.baidu.com/sw-search-sp/soft/2a/25677/QQ_V4.1.1.1456905733.dmg"
/*開始下載
繼續(xù)下載*/
@IBAction func start(sender: AnyObject) {
WhdeBreakPoint.asynDownload(urlStr!, progress: { (progress, receiveByte, allByte) in
self.progressView.progress = progress
self.progressLabel.text = "\(Int.init(progress*100))%"
}, success: { (filePath) in
print("success:"+(filePath as String))
}) { (filePath) in
print("success:"+(filePath as String))
}
}
/*根據(jù)Url暫停*/
@IBAction func pause(sender: AnyObject) {
WhdeBreakPoint.pause(urlStr!)
}
/*根據(jù)Url去刪除文件*/
@IBAction func deleteFile(sender: AnyObject) {
WhdeFileManager.deleteFile(NSURL.init(string: urlStr!)!)
}