[2018/05/11 下部追記]
一個にまとまっとけよ!!
ってことでとりあえずソース
※CryptoSwiftだけLicenseが独自なので注意。他はMIT
おもむろにimport追加しつつ
import Alamofire
import CryptoSwift
import SSZipArchive
// 対象ファイルをダウンロード
let url = "なんかほしいファイルのURL"
let fileName = "保存するファイル名"
// ダウンロード後解凍して元データは要らなくなるのでcache配下に置くように設定している
let downloadPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] + "/" + fileName
let downloadUrl = URL(fileURLWithPath: downloadPath)
// 以下のリクエスト処理が終わるのを待つための変数
let semaphore = DispatchSemaphore(value: 0)
// メインメソッド上でWaitするとデッドロックする問題の回避用
let queue = DispatchQueue.global(qos: .utility)
// MD5値は保存前のデータでやると楽だったので保存用のパラメータ
var md5:Data? = nil
/*
* 進行状況表示用のプログレスバー
*/
let progressView:UIProgressView = UIProgressView(frame: CGRect(x:controller.view.frame.width / 2 - 100, y:controller.view.frame.height / 2 - 5, width:200, height:10))
// ゲージ色の設定
progressView.progressTintColor = UIColor.blue
// ゲージの背景色の設定
progressView.trackTintColor = UIColor.gray
// ゲージの初期値を設定
progressView.progress = 0.0
// ViewにprogressViewをSubViewとして追加
self.view.addSubview(progressView)
// ダウンロード処理
Alamofire.download(url)
.downloadProgress(queue: queue) { progress in
DispatchQueue.main.async(execute: {
progressView.progress = Float(progress.fractionCompleted)
})
}
.responseData(queue: queue) { response in
if let data = response.result.value {
do {
md5 = data.md5()
try data.write(to: downloadUrl)
} catch {
// なんかエラー処理
}
}
// 処理終了を通知
semaphore.signal()
}
// 処理終了まで待機
semaphore.wait()
// MD5確認
if md5 == nil {
// なんかエラー処理
}
if "正しいMD5値" != md5!.toHexString() {
// なんかエラー処理
}
// 解凍してフォルダに配置
if !SSZipArchive.unzipFile(atPath: downloadPath, toDestination: "解凍先のフォルダPath") {
// なんかエラー処理
}
// 終わったらプログレスバーを消す
progressView.removeFromSuperview()
ダウンロードに関してはプログレスバー出してますが
まぁ出すよねっていうあれです。
CocoaPodsの設定は以下
pod "Alamofire", '~> 4.5'
pod 'SwiftyStoreKit'
pod 'CryptoSwift'
pod 'SSZipArchive'
各LibraryのGithubの記述のままだと思います。
いろんなサイトを参考にしましたが、もう全然覚えてない。。。
まぁ基本はLibraryそれぞれのGitHubの記述参考にしてると思います。
--
そこまで大きくないファイルでは非常に有効だったのですが
ファイルサイズが数十MBになったときにCryptoSwiftのMD5取得処理が
非常に時間がかかるようになったので諦めて以下の方法に変更しました。
Object-Cで書くためブリッジヘッダーを作成して
https://gist.github.com/bleft/364d64b36974097f6f8f62001676e108
上記URLの処理を使いました。
このGitには書いてないですが
ブリッジヘッダーに
#import <CommonCrypto/CommonCrypto.h>
を忘れずに追記してください。