Swift - RxSwift的使用詳解48(結(jié)合RxAlamofire使用4:文件下載)

七、文件下載

1,自定義下載文件的保存目錄

(1)下面代碼將 logo 圖片下載下來,并保存到用戶文檔目錄下(Documnets 目錄),文件名不變。

//指定下載路徑(文件名不變)
let destination: DownloadRequest.DownloadFileDestination = { _, response in
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileURL = documentsURL.appendingPathComponent(response.suggestedFilename!)
    //兩個參數(shù)表示如果有同名文件則會覆蓋,如果路徑中文件夾不存在則會自動創(chuàng)建
    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
 
//需要下載的文件
let fileURL = URL(string: "http://www.hangge.com/blog/images/logo.png")!
 
//開始下載
download(URLRequest(url: fileURL), to: destination)
    .subscribe(onNext: { element in
        print("開始下載。")
    }, onError: { error in
        print("下載失敗! 失敗原因:\(error)")
    }, onCompleted: {
        print("下載完畢!")
    })
    .disposed(by: disposeBag)

(2)將 logo 圖片下載下來,并保存到用戶文檔目錄下的 file1 子目錄( Documnets/file1 目錄),文件名改成 myLogo.png。

//指定下載路徑和保存文件名
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileURL = documentsURL.appendingPathComponent("file1/myLogo.png")
    //兩個參數(shù)表示如果有同名文件則會覆蓋,如果路徑中文件夾不存在則會自動創(chuàng)建
    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
 
//需要下載的文件
let fileURL = URL(string: "http://www.hangge.com/blog/images/logo.png")!
 
//開始下載
download(URLRequest(url: fileURL), to: destination)
    .subscribe(onNext: { element in
        print("開始下載。")
    }, onError: { error in
        print("下載失敗! 失敗原因:\(error)")
    }, onCompleted: {
        print("下載完畢!")
    })
    .disposed(by: disposeBag)

2,使用默認(rèn)提供的下載路徑

Alamofire 內(nèi)置的許多常用的下載路徑方便我們使用,簡化代碼。注意的是,使用這種方式如果下載路徑下有同名文件,不會覆蓋原來的文件。

比如,下載到用戶文檔目錄下可以改成:

let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)

3,下載進(jìn)度

(1)下面代碼在文件下載過程中會不斷地打印出當(dāng)前下載進(jìn)度、已下載部分的大小、以及文件總大?。▎挝欢际亲止?jié))。

//開始下載
download(URLRequest(url: fileURL), to: destination)
    .subscribe(onNext: { element in
        print("開始下載。")
        element.downloadProgress(closure: { progress in
            print("當(dāng)前進(jìn)度: \(progress.fractionCompleted)")
            print("  已下載:\(progress.completedUnitCount/1024)KB")
            print("  總大?。篭(progress.totalUnitCount/1024)KB")
        })
    }, onError: { error in
        print("下載失敗! 失敗原因:\(error)")
    }, onCompleted: {
        print("下載完畢!")
    }).disposed(by: disposeBag)

(2)下面我換種寫法,將進(jìn)度轉(zhuǎn)成可觀察序列,并綁定到進(jìn)度條上顯示。

//開始下載
download(URLRequest(url: fileURL), to: destination)
    .map{request in
        //返回一個關(guān)于進(jìn)度的可觀察序列
        Observable<Float>.create{observer in
            request.downloadProgress(closure: { (progress) in
                observer.onNext(Float(progress.fractionCompleted))
                if progress.isFinished{
                    observer.onCompleted()
                }
            })
            return Disposables.create()
        }
    }
    .flatMap{$0}
    .bind(to: progressView.rx.progress) //將進(jìn)度綁定UIProgressView上
    .disposed(by: disposeBag)

RxSwift使用詳解系列
原文出自:www.hangge.com轉(zhuǎn)載請保留原文鏈接

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,983評論 25 709
  • .bat腳本基本命令語法 目錄 批處理的常見命令(未列舉的命令還比較多,請查閱幫助信息) 1、REM 和 :: 2...
    慶慶慶慶慶閱讀 8,532評論 1 19
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評論 19 139
  • 江畔紅 江水悠悠思緒流, 滾滾情長舟滿疇。 莫道桃花江畔蕪, 三石伊始盈君開。
    心放飛閱讀 163評論 0 0
  • 我想告訴你塵封多年的舊事 雨水打濕了泛黃的信箋 好似老婦人思念故人的淚 精心疊制的紫色千紙鶴 裹著回憶的酸 沾著往...
    陸心遠(yuǎn)閱讀 348評論 5 24

友情鏈接更多精彩內(nèi)容