Moya 如何实现文件下载

FileWebService.swift

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
    }()
    
}

推荐阅读更多精彩内容

  • Swift从2014年发布到现在,马上接近三年,经过苹果的不断改进和完善,语法方面已经趋于稳定。如果是新建的项目,...
    Lebron_James阅读 8,008评论 4 43
  • 如今,出门带现金的人越来越少,不论点餐、叫车,还是去剪发、逛超市,所有涉及到的日常支付环节都可以轻松靠刷二维码完成...
    王诗文circle阅读 897评论 9 11
  • 那年,大连的城市道路普遍开始返修、扩建。也是这个季节,凌水至小平岛的路正在施工。 有一天在大连办完事,傍晚准备...
    大哉乾元史蒂夫阅读 181评论 0 1
  • 吼叫着 愤怒着 那是血与肉的生灵 原始的呐喊 唯一的武器如何失去绽裂的伤口 听到那跳动的脉搏了么是血液在尖叫 撕碎...
    平由阅读 245评论 0 2