How to use Moya to download file

Viewed 5527

Usual I use Alamofire & Moya/RxSwift & ObjectMapper to analysis object But now add a demand. My app need download file.

I have use

Alamofire.download(urlString, to: destination) 

Temporary solved the problem

but It's not elegant.

I want use Moya to Maintain the same network layer.

Can you show a Download Moya"s "TargetType"

3 Answers

@Tony, you have two options according current Moya API.

/// A file download task to a destination.
case downloadDestination(DownloadDestination)

/// A file download task to a destination with extra parameters using the given encoding.
case downloadParameters(parameters: [String: Any], encoding: ParameterEncoding, destination: DownloadDestination)

try wit this code to use custom path to save the file

var task: Task {
    switch self {
    case .getFile(let request):
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let devFolderUrl = documentsDirectory[0].appendingPathComponent("\yourfolder")
        let fileUrl = devFolderUrl.appendingPathComponent("\filename.ext")
        var downloadDest: DownloadDestination {
            return { _, _ in return (fileUrl, [.removePreviousFile, .createIntermediateDirectories]) }
        }
        
        return .downloadDestination(downloadDest)
    }
}
Related