feat: 添加中文注释
This commit is contained in:
parent
fc5735964f
commit
ace3e3dd14
Binary file not shown.
@ -1,31 +1,31 @@
|
||||
import SwiftUI
|
||||
import AuthenticationServices
|
||||
import Alamofire
|
||||
import CryptoKit
|
||||
import AuthenticationServices // 苹果登录功能
|
||||
import Alamofire // 网络请求
|
||||
import CryptoKit // 加密功能
|
||||
|
||||
/// Main login view that handles Apple Sign In
|
||||
/// 主登录视图 - 处理苹果登录
|
||||
struct LoginView: View {
|
||||
// MARK: - Properties
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var isLoading = false
|
||||
@State private var showError = false
|
||||
@State private var errorMessage = ""
|
||||
@State private var currentNonce: String?
|
||||
// MARK: - 属性
|
||||
@Environment(\.dismiss) private var dismiss // 用于关闭视图
|
||||
@State private var isLoading = false // 加载状态
|
||||
@State private var showError = false // 是否显示错误
|
||||
@State private var errorMessage = "" // 错误信息
|
||||
@State private var currentNonce: String? // 用于防止重放攻击的随机数
|
||||
|
||||
// MARK: - Body
|
||||
// MARK: - 视图主体
|
||||
var body: some View {
|
||||
ZStack {
|
||||
// Background
|
||||
// 背景
|
||||
Color(.systemBackground)
|
||||
.edgesIgnoringSafeArea(.all)
|
||||
|
||||
// Main content
|
||||
// 主要内容
|
||||
VStack(spacing: 24) {
|
||||
Spacer()
|
||||
appHeaderView()
|
||||
signInButton()
|
||||
appHeaderView() // 应用标题
|
||||
signInButton() // 登录按钮
|
||||
Spacer()
|
||||
termsAndPrivacyView()
|
||||
termsAndPrivacyView() // 服务条款和隐私政策
|
||||
}
|
||||
.padding()
|
||||
.alert(isPresented: $showError) {
|
||||
@ -36,7 +36,7 @@ struct LoginView: View {
|
||||
)
|
||||
}
|
||||
|
||||
// Loading indicator
|
||||
// 加载指示器
|
||||
if isLoading {
|
||||
loadingView()
|
||||
}
|
||||
@ -44,9 +44,9 @@ struct LoginView: View {
|
||||
.navigationBarHidden(true)
|
||||
}
|
||||
|
||||
// MARK: - View Components
|
||||
// MARK: - 视图组件
|
||||
|
||||
/// App header with icon and welcome text
|
||||
/// 应用标题视图
|
||||
private func appHeaderView() -> some View {
|
||||
VStack(spacing: 16) {
|
||||
Image(systemName: "person.circle.fill")
|
||||
@ -66,27 +66,27 @@ struct LoginView: View {
|
||||
.padding(.bottom, 40)
|
||||
}
|
||||
|
||||
/// Apple Sign In button
|
||||
/// 苹果登录按钮
|
||||
private func signInButton() -> some View {
|
||||
SignInWithAppleButton(
|
||||
onRequest: { request in
|
||||
// Generate nonce for security
|
||||
// 生成随机数用于安全验证
|
||||
let nonce = String.randomURLSafeString(length: 32)
|
||||
self.currentNonce = nonce
|
||||
|
||||
// Configure the request
|
||||
request.requestedScopes = [.fullName, .email]
|
||||
request.nonce = self.sha256(nonce)
|
||||
// 配置登录请求
|
||||
request.requestedScopes = [.fullName, .email] // 请求用户全名和邮箱
|
||||
request.nonce = self.sha256(nonce) // 设置nonce
|
||||
},
|
||||
onCompletion: handleAppleSignIn
|
||||
onCompletion: handleAppleSignIn // 登录完成处理
|
||||
)
|
||||
.signInWithAppleButtonStyle(.black)
|
||||
.signInWithAppleButtonStyle(.black) // 按钮样式
|
||||
.frame(height: 50)
|
||||
.padding(.horizontal, 40)
|
||||
.cornerRadius(10)
|
||||
}
|
||||
|
||||
/// Terms and Privacy policy links
|
||||
/// 服务条款和隐私政策链接
|
||||
private func termsAndPrivacyView() -> some View {
|
||||
VStack(spacing: 8) {
|
||||
Text("By continuing, you agree to our")
|
||||
@ -113,7 +113,7 @@ struct LoginView: View {
|
||||
.padding(.bottom, 24)
|
||||
}
|
||||
|
||||
/// Loading overlay view
|
||||
/// 加载视图
|
||||
private func loadingView() -> some View {
|
||||
return ZStack {
|
||||
Color.black.opacity(0.4)
|
||||
@ -125,9 +125,9 @@ struct LoginView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Apple Sign In Handlers
|
||||
// MARK: - 苹果登录处理
|
||||
|
||||
/// Handles the result of Apple Sign In
|
||||
/// 处理苹果登录结果
|
||||
private func handleAppleSignIn(result: Result<ASAuthorization, Error>) {
|
||||
switch result {
|
||||
case .success(let authResults):
|
||||
@ -137,14 +137,14 @@ struct LoginView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Processes the Apple ID credential
|
||||
/// 处理苹果ID凭证
|
||||
private func processAppleIDCredential(_ credential: ASAuthorizationCredential) {
|
||||
guard let appleIDCredential = credential as? ASAuthorizationAppleIDCredential else {
|
||||
showError(message: "Unable to process Apple ID credentials")
|
||||
showError(message: "无法处理Apple ID凭证")
|
||||
return
|
||||
}
|
||||
|
||||
// Get user data
|
||||
// 获取用户数据
|
||||
let userId = appleIDCredential.user
|
||||
let email = appleIDCredential.email ?? ""
|
||||
let fullName = [
|
||||
@ -154,20 +154,20 @@ struct LoginView: View {
|
||||
.compactMap { $0 }
|
||||
.joined(separator: " ")
|
||||
|
||||
// Get the identity token
|
||||
// 获取身份令牌
|
||||
guard let identityTokenData = appleIDCredential.identityToken,
|
||||
let identityToken = String(data: identityTokenData, encoding: .utf8) else {
|
||||
showError(message: "Unable to fetch identity token")
|
||||
showError(message: "无法获取身份令牌")
|
||||
return
|
||||
}
|
||||
|
||||
// Get the authorization code (optional)
|
||||
// 获取授权码(可选)
|
||||
var authCode: String? = nil
|
||||
if let authCodeData = appleIDCredential.authorizationCode {
|
||||
authCode = String(data: authCodeData, encoding: .utf8)
|
||||
}
|
||||
|
||||
// Proceed with backend authentication
|
||||
// 调用后端接口进行认证
|
||||
authenticateWithBackend(
|
||||
userId: userId,
|
||||
email: email,
|
||||
@ -177,9 +177,9 @@ struct LoginView: View {
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Network Operations
|
||||
// MARK: - 网络操作
|
||||
|
||||
/// Authenticates the user with the backend server
|
||||
/// 与后端服务器进行认证
|
||||
private func authenticateWithBackend(
|
||||
userId: String,
|
||||
email: String,
|
||||
@ -189,6 +189,7 @@ struct LoginView: View {
|
||||
) {
|
||||
isLoading = true
|
||||
|
||||
// TODO: 替换为您的后端API地址
|
||||
let url = "https://your-api-endpoint.com/api/auth/apple"
|
||||
var parameters: [String: Any] = [
|
||||
"appleUserId": userId,
|
||||
@ -197,11 +198,12 @@ struct LoginView: View {
|
||||
"identityToken": identityToken
|
||||
]
|
||||
|
||||
// Add authorization code if available
|
||||
// 添加授权码(如果存在)
|
||||
if let authCode = authCode {
|
||||
parameters["authorizationCode"] = authCode
|
||||
}
|
||||
|
||||
// 发送认证请求
|
||||
AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
|
||||
.validate()
|
||||
.responseJSON { response in
|
||||
@ -209,7 +211,7 @@ struct LoginView: View {
|
||||
|
||||
switch response.result {
|
||||
case .success(let value):
|
||||
print("Authentication successful: \(value)")
|
||||
print("认证成功: \(value)")
|
||||
self.handleSuccessfulAuthentication()
|
||||
case .failure(let error):
|
||||
self.handleAuthenticationError(error)
|
||||
@ -217,30 +219,30 @@ struct LoginView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helper Methods
|
||||
// MARK: - 辅助方法
|
||||
|
||||
/// Handles successful authentication
|
||||
/// 处理认证成功
|
||||
private func handleSuccessfulAuthentication() {
|
||||
DispatchQueue.main.async {
|
||||
self.dismiss()
|
||||
self.dismiss() // 关闭登录视图
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles sign in errors
|
||||
/// 处理登录错误
|
||||
private func handleSignInError(_ error: Error) {
|
||||
let errorMessage = (error as NSError).localizedDescription
|
||||
print("Apple Sign In failed: \(errorMessage)")
|
||||
showError(message: "Sign in failed: \(error.localizedDescription)")
|
||||
print("苹果登录失败: \(errorMessage)")
|
||||
showError(message: "登录失败: \(error.localizedDescription)")
|
||||
}
|
||||
|
||||
/// Handles authentication errors
|
||||
/// 处理认证错误
|
||||
private func handleAuthenticationError(_ error: AFError) {
|
||||
let errorMessage = error.localizedDescription
|
||||
print("API Error: \(errorMessage)")
|
||||
showError(message: "Failed to sign in: \(errorMessage)")
|
||||
print("API错误: \(errorMessage)")
|
||||
showError(message: "登录失败: \(errorMessage)")
|
||||
}
|
||||
|
||||
/// Shows error message to the user
|
||||
/// 显示错误信息
|
||||
private func showError(message: String) {
|
||||
DispatchQueue.main.async {
|
||||
self.errorMessage = message
|
||||
@ -248,12 +250,13 @@ struct LoginView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a URL in Safari
|
||||
/// 在Safari中打开URL
|
||||
private func openURL(_ string: String) {
|
||||
guard let url = URL(string: string) else { return }
|
||||
UIApplication.shared.open(url)
|
||||
}
|
||||
|
||||
/// SHA256哈希函数
|
||||
private func sha256(_ input: String) -> String {
|
||||
let inputData = Data(input.utf8)
|
||||
let hashedData = SHA256.hash(data: inputData)
|
||||
@ -262,12 +265,12 @@ struct LoginView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - String Extension for Random String Generation
|
||||
// MARK: - 字符串扩展:生成随机字符串
|
||||
|
||||
extension String {
|
||||
/// Generates a random string of the specified length using URL-safe characters
|
||||
/// - Parameter length: The length of the random string to generate
|
||||
/// - Returns: A random string containing URL-safe characters
|
||||
/// 生成指定长度的随机URL安全字符串
|
||||
/// - Parameter length: 字符串长度
|
||||
/// - Returns: 随机字符串
|
||||
static func randomURLSafeString(length: Int) -> String {
|
||||
let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"
|
||||
var randomString = ""
|
||||
@ -282,7 +285,7 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Preview
|
||||
// MARK: - 预览
|
||||
struct LoginView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
LoginView()
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user