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

105 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: - Generate Blind Box Request Model
// struct GenerateBlindBoxRequest: Codable {
// let boxType: String
// let materialIds: [String]
// enum CodingKeys: String, CodingKey {
// case boxType = "box_type"
// case materialIds = "material_ids"
// }
// }
// MARK: - Generate Blind Box Response Model
struct GenerateBlindBoxResponse: Codable {
let code: Int
let data: BlindBoxData?
}
// MARK: - Blind Box API Client
class BlindBoxApi {
static let shared = BlindBoxApi()
private init() {}
///
/// - Parameters:
/// - boxType: ( "First")
/// - materialIds: ID
/// - completion:
func generateBlindBox(
boxType: String,
materialIds: [String],
completion: @escaping (Result<BlindBoxData?, Error>) -> Void
) {
// Codable
let parameters: [String: Any] = [
"box_type": boxType,
"material_ids": materialIds
]
NetworkService.shared.postWithToken(
path: "/blind_box/generate",
parameters: parameters,
completion: { (result: Result<GenerateBlindBoxResponse, 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):
completion(.failure(error))
}
}
}
)
}
///
/// - Parameters:
/// - boxId: ID
/// - completion:
func getBlindBox(
boxId: String,
completion: @escaping (Result<BlindBoxData?, Error>) -> Void
) {
let path = "/blind_box/query/\(boxId)"
NetworkService.shared.getWithToken(
path: path,
completion: { (result: Result<GenerateBlindBoxResponse, 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):
completion(.failure(error))
}
}
}
)
}
/// 使 async/await
/// - Parameter boxId: ID
/// - Returns:
@available(iOS 13.0, *)
func getBlindBox(boxId: String) async throws -> BlindBoxData? {
let path = "/blind_box/query/\(boxId)"
let response: GenerateBlindBoxResponse = try await NetworkService.shared.getWithToken(path: path)
if response.code == 0 {
return response.data
} else {
throw NetworkError.serverError("服务器返回错误码: \(response.code)")
}
}
}