wake-ios/wake/View/Components/Upload/MaterialService.swift
2025-08-19 20:36:00 +08:00

63 lines
2.1 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
///
class MaterialService {
///
static let shared = MaterialService()
private init() {}
///
/// - Parameters:
/// - fileId: ID
/// - previewFileId: ID
/// - completion:
func uploadMaterialInfo(fileId: String,
previewFileId: String,
completion: @escaping (Bool, String?) -> Void) {
let materialData: [[String: String]] = [[
"file_id": fileId,
"preview_file_id": previewFileId
]]
guard let url = URL(string: "\(APIConfig.baseURL)/material") else {
completion(false, "无效的URL")
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = APIConfig.authHeaders
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: materialData)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
completion(false, "上传失败: \(error.localizedDescription)")
return
}
if let httpResponse = response as? HTTPURLResponse {
if (200...299).contains(httpResponse.statusCode) {
completion(true, nil)
} else {
let statusCode = httpResponse.statusCode
completion(false, "服务器返回错误状态码: \(statusCode)")
}
} else {
completion(false, "无效的服务器响应")
}
}
task.resume()
} catch {
completion(false, "请求数据序列化失败: \(error.localizedDescription)")
}
}
}