IOS_Boss/IOS_study/Manager/RESTManager.swift
2025-07-27 12:33:06 +08:00

107 lines
5.3 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.

//
// RESTManager.swift
// IOS_study
//
// Created by CC-star on 2025/7/3.
//
import Foundation
final class RESTManager {
static let shared = RESTManager()
private init() {}//RESTManagerclass
//REST API
func findOne<T: Decodable>(form urlStr: String) async throws -> T {
guard let url = URL(string: urlStr) else { throw URLError(.badURL) }
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(kAppID, forHTTPHeaderField: "X-LC-Id")
request.setValue(kAppKey, forHTTPHeaderField: "X-LC-Key")
let (data, response) = try await URLSession.shared.data(for: request)
//print(String(data: data, encoding: .utf8) ?? "Invalid data")
guard let httpRespsonse = response as? HTTPURLResponse, 200..<300 ~= httpRespsonse.statusCode else { throw URLError(.badServerResponse) }
let decoder = JSONDecoder()
//decoder.keyDecodingStrategy = .convertFromSnakeCase//线
//Date
decoder.dateDecodingStrategy = .custom { decoder -> Date in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] //
if let date = isoFormatter.date(from: dateString) { return date }
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date format: \(dateString)")
}
return try decoder.decode( T.self, from: data)
}
//REST API
func find<T: Decodable>(form urlStr: String) async throws ->[T] {
guard let url = URL(string: urlStr) else { throw URLError(.badURL) }
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(kAppID, forHTTPHeaderField: "X-LC-Id")
request.setValue(kAppKey, forHTTPHeaderField: "X-LC-Key")
let (data,_) = try await URLSession.shared.data(for: request)
//print(String(data: data, encoding: .utf8) ?? "Invalid data")
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let results = json["results"] as? [[String: Any]] else {
throw URLError(.cannotParseResponse)
}
let decoder = JSONDecoder()
//decoder.keyDecodingStrategy = .convertFromSnakeCase//线
//Date
decoder.dateDecodingStrategy = .custom { decoder -> Date in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] //
if let date = isoFormatter.date(from: dateString) { return date }
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date format: \(dateString)")
}
let tData = try JSONSerialization.data(withJSONObject: results)
return try decoder.decode([T].self, from: tData)
}
//REST API
func save<T: Encodable>(to urlStr: String, object: T) async throws {//TEncodable
guard let url = URL(string: urlStr) else { throw NetworkError.invalidURL// ->
}//urlelse
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(kAppID, forHTTPHeaderField: "X-LC-Id")
request.setValue(kAppKey, forHTTPHeaderField: "X-LC-Key")
let encoder = JSONEncoder()
// encoder.keyEncodingStrategy = .convertToSnakeCase//线
request.httpBody = try encoder.encode(object)//使LeanCloud RESTDate
let (data, response) = try await URLSession.shared.data(for: request)//
guard let httpRespsonse = response as? HTTPURLResponse else { throw NetworkError.notHTTPResponse }
if !(200..<300).contains(httpRespsonse.statusCode) {// 2 -> [200,300)
let errRespsonse = try JSONSerialization.jsonObject(with: data) as? [String: Any]//Any
let errMsg = errRespsonse?["error"] as? String ?? "响应数据类型转换失败"
//errRespsonseerror
//errRespsonse?["error"] as? String??
throw NetworkError.requestFailed("错误码:\(httpRespsonse.statusCode),错误信息:\(errMsg)")
}
}
}