Created
July 27, 2017 08:52
-
-
Save pandaApe/fac2615f729c9a0cf6bab29700416747 to your computer and use it in GitHub Desktop.
Moya Download File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Moya | |
let endpointClosure = { | |
(target: FileService) -> Endpoint<FileService> in | |
let url = URL(string: target.path)?.absoluteString | |
return Endpoint(URL: url!,enter code here sampleResponseClosure: { .networkResponse(200, target.sampleData) }, method: target.method, parameters: target.parameters) | |
} | |
private func JSONResponseDataFormatter(_ data: Data) -> Data { | |
do { | |
let dataAsJSON = try JSONSerialization.jsonObject(with: data) | |
let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted) | |
return prettyData | |
} catch { | |
return data // fallback to original data if it can't be serialized. | |
} | |
} | |
let FileDownloadProvider = RxMoyaProvider<FileService>(endpointClosure: endpointClosure, plugins: [NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)]) | |
enum FileService { | |
case download(url: String) | |
} | |
extension FileService:TargetType{ | |
var baseURL : URL{ | |
return URL(string:"http://no.use.but.cant.empty")! | |
} | |
var path:String{ | |
switch self { | |
case .download(let url): | |
return url | |
} | |
} | |
var method: Moya.Method { | |
switch self { | |
case .download: | |
return .get | |
} | |
} | |
var parameters: [String:Any]?{ | |
switch self { | |
case .download: | |
return nil | |
} | |
} | |
var sampleData:Data{ | |
switch self { | |
default: | |
return "default data".utf8EncodedData | |
} | |
} | |
var task:Task{ | |
switch self { | |
case .download: | |
return .download(DownloadType.request(DefaultDownloadDestination)) | |
} | |
} | |
} | |
private let DefaultDownloadDestination: DownloadDestination = { temporaryURL, response in | |
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] | |
let fileURL = documentsURL.appendingPathComponent(response.suggestedFilename!) | |
return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) | |
} | |
// MARK: - Helpers | |
private extension String { | |
var urlEscapedString: String { | |
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! | |
} | |
var utf8EncodedData: Data { | |
return self.data(using: .utf8)! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment