import Moya
import SwiftyJSON
enum FileWebService {
case download(url: String, fileName: String?)
var localLocation: URL {
switch self {
case .download(let url, let fileName):
let fileKey: String = url.MD5 // use url's md5 as local file name
let directory: URL = FileSystem.downloadDirectory
var filePath: URL = directory.appendingPathComponent(fileKey)
if let name = fileName {
// append path extension if exit
let pathExtension: String = (name as NSString).pathExtension.lowercased()
filePath = filePath.appendingPathExtension(pathExtension)
}
return filePath
}
}
var downloadDestination: DownloadDestination {
// `createIntermediateDirectories` will create directories in file path
return { _, _ in return (self.localLocation, [.removePreviousFile, .createIntermediateDirectories]) }
}
}
extension FileWebService: TargetType {
var baseURL: URL {
switch self {
case .download(let url, _):
return URL(string: url)!
}
}
var path: String {
switch self {
case .download(_, _):
return ""
}
}
var method: Moya.Method {
switch self {
case .download(_, _):
return .get
}
}
var parameters: [String: Any]? {
switch self {
case .download:
return nil
}
}
var parameterEncoding: ParameterEncoding {
return URLEncoding.default
}
var task: Task {
switch self {
case .download(_, _):
return .download(.request(downloadDestination))
}
}
var sampleData: Data {
return Data()
}
var headers: [String: String]? {
return nil
}
}
struct FileProvider {
static let provider = MoyaProvider<FileWebService>(plugins: [NetworkLoggerPlugin(verbose: WebService.verbose)])
static func request(target: FileWebService, progress: ProgressBlock?, completion: @escaping (WebService.Result) -> Void) -> Cancellable {
return provider.request(target, progress: progress) { result in
switch result {
case let .success(response):
let data = response.data
let json = JSON(data: data)
completion(.success(json))
case .failure(_):
completion(.failure("download fail"))
}
}
}
}
class WebService {
// set false when release
static var verbose: Bool = true
// response result type
enum Result {
case success(JSON)
case failure(String)
}
}
class FileSystem {
static let documentsDirectory: URL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.endIndex - 1]
}()
static let cacheDirectory: URL = {
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return urls[urls.endIndex - 1]
}()
static let downloadDirectory: URL = {
let directory: URL = FileSystem.documentsDirectory.appendingPathComponent("/Download/")
return directory
}()
}
Moya 如何实现文件下载
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Swift从2014年发布到现在,马上接近三年,经过苹果的不断改进和完善,语法方面已经趋于稳定。如果是新建的项目,...