XuqmGroup-iOSSDK/XuqmDemo/Sources/ViewModels/AuthViewModel.swift
2026-05-07 19:39:48 +08:00

50 行
1.6 KiB
Swift

import Foundation
import XuqmSDK
@MainActor
final class AuthViewModel: ObservableObject {
@Published var state: LoginState = .idle
@Published var currentUserId: String = ""
@Published var currentNickname: String = ""
private struct DemoLoginResponse: Decodable, Sendable {
let imToken: String
let profile: DemoProfile
struct DemoProfile: Decodable, Sendable {
let userId: String
}
}
func login(userId: String, password: String) {
guard !userId.isEmpty, !password.isEmpty else {
state = .error("请输入用户 ID 和密码")
return
}
state = .loading
Task {
do {
let config = XuqmSDK.shared.requireConfig()
let res: DemoLoginResponse = try await ApiClient.shared.request(
path: "/api/demo/auth/login",
method: "POST",
queryItems: [URLQueryItem(name: "appKey", value: config.appKey)],
body: ["appKey": config.appKey, "userId": userId, "password": password]
)
await XuqmSDK.shared.login(userId: res.profile.userId, userSig: res.imToken)
currentUserId = res.profile.userId
currentNickname = res.profile.userId
state = .success
} catch {
state = .error(error.localizedDescription)
}
}
}
func logout() {
Task { await XuqmSDK.shared.logout() }
currentUserId = ""
currentNickname = ""
state = .idle
}
}