wake-ios/wake/Utils/ApiClient/MaterialUpload.swift

113 lines
3.5 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Foundation
// MARK: -
struct MaterialRequest: Codable {
let fileId: String
let previewFileId: String
enum CodingKeys: String, CodingKey {
case fileId = "file_id"
case previewFileId = "preview_file_id"
}
}
struct AddMaterialResponse: Codable {
let code: Int
let data: [String]?
}
// MARK: -
class MaterialUpload {
static let shared = MaterialUpload()
private init() {}
///
/// - Parameters:
/// - fileId: ID
/// - previewFileId: ID
/// - completion: ID
func addMaterial(
fileId: String,
previewFileId: String,
completion: @escaping (Result<[String]?, Error>) -> Void
) {
//
let materials: [[String: String]] = [[
"file_id": fileId,
"preview_file_id": previewFileId
]]
// JSON
print("🔍 准备发送的参数: \(materials)")
// 使NetworkService
NetworkService.shared.post(
path: "/material",
parameters: materials,
completion: { (result: Result<AddMaterialResponse, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
if response.code == 0 {
completion(.success(response.data))
} else {
completion(.failure(NetworkError.serverError("服务器返回错误码: \(response.code)")))
}
case .failure(let error):
print("❌ 素材上传失败: \(error.localizedDescription)")
completion(.failure(error))
}
}
}
)
}
/// 使 async/await
/// - Parameters:
/// - fileId: ID
/// - previewFileId: ID
/// - Returns: ID
/// - Throws: NetworkError
func addMaterial(
fileId: String,
previewFileId: String
) async throws -> [String]? {
//
let materials: [[String: String]] = [[
"file_id": fileId,
"preview_file_id": previewFileId
]]
//
print("🔍(async) 准备发送的参数: \(materials)")
// 使 async/await post
let response: AddMaterialResponse = try await NetworkService.shared.post(
path: "/material",
parameters: materials
)
// code
if response.code == 0 {
return response.data
} else {
throw NetworkError.serverError("服务器返回错误码: \(response.code)")
}
}
func addMaterials(files: [[String: String]]) async throws -> [String]? {
let response: AddMaterialResponse = try await NetworkService.shared.post(
path: "/material",
parameters: files
)
if response.code == 0 {
return response.data
} else {
throw NetworkError.serverError("服务器返回错误码: \(response.code)")
}
}
}