添加网络层并接入 v9 登录流程及单元测试

This commit is contained in:
2026-07-06 15:33:34 +08:00
parent 31ffec0f2b
commit d424928243
21 changed files with 2387 additions and 18 deletions

View File

@ -0,0 +1,264 @@
//
// APIClient.swift
// suixinkan
//
import Foundation
/// URLSession
protocol URLSessionProtocol {
/// URLRequest
func data(for request: URLRequest) async throws -> (Data, URLResponse)
}
extension URLSession: URLSessionProtocol {}
@MainActor
/// token Envelope
final class APIClient {
private let session: URLSessionProtocol
private let encoder: JSONEncoder
private let decoder: JSONDecoder
private var authTokenProvider: (() -> String?)?
private let environment: APIEnvironment
private let appVersion: String
private let osType: String
///
init(
environment: APIEnvironment = .current,
session: URLSessionProtocol = APIClient.defaultSession,
encoder: JSONEncoder = JSONEncoder(),
decoder: JSONDecoder = JSONDecoder(),
appVersion: String = AppClientInfo.appVersion(),
osType: String = AppClientInfo.osType
) {
self.environment = environment
self.session = session
self.encoder = encoder
self.decoder = decoder
self.appVersion = appVersion.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? "1.0.0"
self.osType = osType.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? AppClientInfo.osType
}
nonisolated private static let defaultSession: URLSession = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 12
configuration.timeoutIntervalForResource = 20
configuration.waitsForConnectivity = false
return URLSession(configuration: configuration)
}()
/// token API
func bindAuthTokenProvider(_ provider: @escaping () -> String?) {
authTokenProvider = provider
}
/// APIRequest
func send<Response: Decodable>(
_ apiRequest: APIRequest<Response>,
tokenOverride: String? = nil
) async throws -> Response {
let request = try makeURLRequest(apiRequest, tokenOverride: tokenOverride)
logRequest(request)
let data: Data
let response: URLResponse
do {
(data, response) = try await session.data(for: request)
} catch is CancellationError {
logCancelled(for: request, reason: "CancellationError")
throw CancellationError()
} catch let error as URLError {
if error.code == .cancelled {
logCancelled(for: request, reason: "URLError.cancelled")
throw CancellationError()
}
throw APIError.networkFailed(networkErrorMessage(for: error))
} catch {
throw APIError.networkFailed(error.localizedDescription)
}
logResponse(for: request, response: response, data: data)
do {
try validateHTTPResponse(response, data: data)
return try decodeEnvelope(Response.self, from: data)
} catch let error as APIError {
notifySessionExpiredIfNeeded(for: error)
throw error
}
}
/// URLRequest Headertoken
private func makeURLRequest<Response: Decodable>(
_ apiRequest: APIRequest<Response>,
tokenOverride: String?
) throws -> URLRequest {
let path = apiRequest.path.hasPrefix("/") ? apiRequest.path : "/" + apiRequest.path
guard var components = URLComponents(
string: environment.baseURL.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + path
) else {
throw APIError.invalidURL
}
if !apiRequest.queryItems.isEmpty {
components.queryItems = apiRequest.queryItems
}
guard let url = components.url else {
throw APIError.invalidURL
}
var request = URLRequest(url: url)
request.httpMethod = apiRequest.method.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue(appVersion, forHTTPHeaderField: "X-APP-VERSION")
request.setValue(osType, forHTTPHeaderField: "X-OS-TYPE")
apiRequest.headers.forEach { key, value in
request.setValue(value, forHTTPHeaderField: key)
}
let token = tokenOverride ?? authTokenProvider?()
if let token = token?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
request.setValue(token, forHTTPHeaderField: "token")
}
if let body = apiRequest.body {
request.httpBody = try encoder.encode(body)
}
return request
}
/// HTTP 2xx
private func validateHTTPResponse(_ response: URLResponse, data: Data) throws {
guard let httpResponse = response as? HTTPURLResponse else {
throw APIError.invalidResponse
}
guard 200 ..< 300 ~= httpResponse.statusCode else {
throw APIError.httpStatus(httpResponse.statusCode, parseHTTPErrorMessage(data: data))
}
}
/// Envelope data
private func decodeEnvelope<Response: Decodable>(_ responseType: Response.Type, from data: Data) throws -> Response {
let envelope: APIEnvelope<Response>
do {
envelope = try decoder.decode(APIEnvelope<Response>.self, from: data)
} catch {
throw APIError.decodeFailed(error.localizedDescription)
}
guard envelope.isSuccess else {
throw APIError.serverCode(envelope.code, envelope.msg ?? "业务请求失败")
}
if responseType == EmptyPayload.self {
return EmptyPayload() as! Response
}
guard let payload = envelope.data else {
throw APIError.emptyData
}
return payload
}
/// Token 广 sessionDidExpire
private func notifySessionExpiredIfNeeded(for error: APIError) {
guard APIError.isAuthenticationExpired(error) else { return }
NotificationCenter.default.post(name: NotificationName.sessionDidExpire, object: nil)
}
/// HTTP
private func parseHTTPErrorMessage(data: Data) -> String {
if let envelope = try? decoder.decode(ErrorEnvelope.self, from: data) {
if let msg = envelope.msg?.trimmingCharacters(in: .whitespacesAndNewlines), !msg.isEmpty {
return msg
}
if let message = envelope.message?.trimmingCharacters(in: .whitespacesAndNewlines), !message.isEmpty {
return message
}
if let error = envelope.error?.trimmingCharacters(in: .whitespacesAndNewlines), !error.isEmpty {
return error
}
}
if let plainText = String(data: data, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines),
!plainText.isEmpty {
return plainText.count > 120 ? String(plainText.prefix(120)) + "..." : plainText
}
return "服务端返回错误"
}
/// URLError
private func networkErrorMessage(for error: URLError) -> String {
switch error.code {
case .timedOut:
"请求超时,请稍后重试"
case .notConnectedToInternet:
"网络不可用,请检查网络连接"
case .networkConnectionLost:
"网络连接中断,请重试"
case .cannotFindHost, .cannotConnectToHost, .dnsLookupFailed:
"无法连接服务器,请稍后重试"
default:
error.localizedDescription
}
}
/// Debug
private func logRequest(_ request: URLRequest) {
#if DEBUG
let method = request.httpMethod ?? "REQUEST"
let url = request.url?.absoluteString ?? "<invalid url>"
print("[API][Request] \(method) \(url)")
#endif
}
/// Debug
private func logResponse(for request: URLRequest, response: URLResponse, data: Data) {
#if DEBUG
let method = request.httpMethod ?? "REQUEST"
let url = request.url?.absoluteString ?? "<invalid url>"
let statusCode = (response as? HTTPURLResponse).map { String($0.statusCode) } ?? "unknown"
let body = Self.debugResponseBody(from: data)
print("[API][Response] \(method) \(url) status=\(statusCode)\n\(body)")
#endif
}
/// Debug
private func logCancelled(for request: URLRequest, reason: String) {
#if DEBUG
let method = request.httpMethod ?? "REQUEST"
let url = request.url?.absoluteString ?? "<invalid url>"
print("[API][Cancelled] \(method) \(url) reason=\(reason)")
#endif
}
#if DEBUG
/// 便
private static func debugResponseBody(from data: Data) -> String {
guard !data.isEmpty else { return "<empty response>" }
if
let object = try? JSONSerialization.jsonObject(with: data),
let prettyData = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]),
let prettyJSON = String(data: prettyData, encoding: .utf8) {
return prettyJSON
}
return String(data: data, encoding: .utf8) ?? "<non-utf8 response: \(data.count) bytes>"
}
#endif
}
private extension String {
var nonEmpty: String? {
isEmpty ? nil : self
}
}

View File

@ -0,0 +1,60 @@
//
// APIEnvelope.swift
// suixinkan
//
import Foundation
/// codemsg data
struct APIEnvelope<T: Decodable>: Decodable {
let data: T?
let code: Int
let msg: String?
/// code
var isSuccess: Bool {
code == 100000
}
/// Envelope JSON
enum CodingKeys: String, CodingKey {
case data
case code
case msg
}
/// data EmptyPayload
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
code = try container.decodeIfPresent(Int.self, forKey: .code) ?? 0
msg = try container.decodeIfPresent(String.self, forKey: .msg)
guard code == 100000 else {
data = nil
return
}
guard container.contains(.data), try !container.decodeNil(forKey: .data) else {
data = nil
return
}
if T.self == EmptyPayload.self {
data = EmptyPayload() as? T
return
}
data = try container.decode(T.self, forKey: .data)
}
}
/// data
struct EmptyPayload: Codable {}
/// HTTP
struct ErrorEnvelope: Decodable {
let code: Int?
let msg: String?
let message: String?
let error: String?
}

View File

@ -0,0 +1,60 @@
//
// APIEnvironment.swift
// suixinkan
//
import Foundation
/// HTTP WebSocket
struct APIEnvironment: Equatable {
let baseURL: URL
let webSocketURL: URL
nonisolated static let production = APIEnvironment(
baseURL: URL(string: "https://api.zhifly.cn")!,
webSocketURL: URL(string: "wss://api.zhifly.cn/wss")!
)
nonisolated static let testing = APIEnvironment(
baseURL: URL(string: "https://api-test.zhifly.cn")!,
webSocketURL: URL(string: "wss://api-test.zhifly.cn/wss")!
)
nonisolated static var current: APIEnvironment {
#if DEBUG
.testing
#else
.production
#endif
}
}
/// App
enum AppClientInfo {
nonisolated static let osType = "iOS"
/// App build
nonisolated static func appVersion(infoDictionary: [String: Any]? = Bundle.main.infoDictionary) -> String {
let version = (infoDictionary?["CFBundleShortVersionString"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
.nonEmpty ?? "1.0.0"
let build = (infoDictionary?["CFBundleVersion"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines)
.nonEmpty
let versionParts = version.split(separator: ".", omittingEmptySubsequences: false)
if versionParts.count >= 3 {
return version
}
if versionParts.count == 2, let build {
return "\(version).\(build)"
}
return version
}
}
private extension String {
nonisolated var nonEmpty: String? {
isEmpty ? nil : self
}
}

View File

@ -0,0 +1,54 @@
//
// APIError.swift
// suixinkan
//
import Foundation
/// URLHTTP
enum APIError: Error, LocalizedError {
case invalidURL
case invalidResponse
case httpStatus(Int, String)
case serverCode(Int, String)
case emptyData
case decodeFailed(String)
case networkFailed(String)
var errorDescription: String? {
switch self {
case .invalidURL:
"请求地址无效"
case .invalidResponse:
"服务响应异常"
case let .httpStatus(statusCode, message):
"请求失败HTTP \(statusCode)\(message)"
case .serverCode(_, let message):
message
case .emptyData:
"接口返回数据为空"
case .decodeFailed(let message):
"数据解析失败:\(message)"
case .networkFailed(let message):
"网络请求失败:\(message)"
}
}
}
extension APIError {
/// Android `NetworkResponse.isTokenFailed` Token
static let tokenInvalidCodes: Set<Int> = [180024, 100091, 100090, 100060]
///
static func isAuthenticationExpired(_ error: Error) -> Bool {
guard let apiError = error as? APIError else { return false }
switch apiError {
case let .httpStatus(statusCode, _):
return statusCode == 401 || statusCode == 403
case let .serverCode(code, _):
return tokenInvalidCodes.contains(code)
default:
return false
}
}
}

View File

@ -0,0 +1,53 @@
//
// APIRequest.swift
// suixinkan
//
import Foundation
/// HTTP
enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
/// API Header
nonisolated struct APIRequest<Response: Decodable> {
var method: HTTPMethod
var path: String
var queryItems: [URLQueryItem]
var headers: [String: String]
var body: AnyEncodable?
/// API AnyEncodable
init<Body: Encodable>(
method: HTTPMethod,
path: String,
queryItems: [URLQueryItem] = [],
headers: [String: String] = [:],
body: Body? = Optional<EmptyPayload>.none
) {
self.method = method
self.path = path
self.queryItems = queryItems
self.headers = headers
self.body = body.map(AnyEncodable.init)
}
}
/// Encodable APIRequest
nonisolated struct AnyEncodable: Encodable, Sendable {
private let encodeValue: @Sendable (Encoder) throws -> Void
init<Value: Encodable>(_ value: Value) {
encodeValue = { encoder in
try value.encode(to: encoder)
}
}
func encode(to encoder: Encoder) throws {
try encodeValue(encoder)
}
}