gpt4 book ai didi

swift - SwiftUI MVVM如何在功能后显示警报

转载 作者:行者123 更新时间:2023-12-03 10:31:01 26 4
gpt4 key购买 nike

我正在使用MVVM体系结构创建用户登录页面,并且如果文本字段为空或用户名/密码错误,我想显示一个警报页面。因此,在单击登录和API调用后,如果登录失败,我想显示一个警报,但是我尝试更改状态,但仍然不显示警报。
登录查看

struct LoginView: View {
@ObservedObject var user: User
@ObservedObject var viewModel = LoginViewModel()
@State var inputUser: String = ""
@State var inputPass: String = ""
@State private var showingAlert = true

var body: some View {
ScrollView {
VStack(alignment: .leading) {
Group {
Text("Login")
CustomTextField(placeHolder: "Username", value: $viewModel.user)
CustomTextField(placeHolder: "Password", value: $viewModel.pass)
Button(action: {
self.viewModel.login { (isSuccess) in
if isSuccess {
self.user.tokenIsActive = true
} else {
// if login failed, show alert, but alert not showing
self.showingAlert = true
}
}
}) {
Text("Sign In")
}.buttonStyle(PrimaryButtonStyle())
.alert(isPresented: $showingAlert) {
Alert(title: Text("Error"), message: Text("Invalid username / password"), dismissButton: .default(Text("Got it!")))
}
}
}
}
}
}
LoginViewModel
class LoginViewModel: ObservableObject, LoginService {
var apiSession: APIService

@Published var user = ""
@Published var pass = ""

@Published var accessToken: String?
@Published var refreshToken: String?
@Published var showingAlert = true

var cancellables = Set<AnyCancellable>()

init(apiSession: APIService = APISession()) {
self.apiSession = apiSession
}

func login(_ completion: @escaping ((Bool)->Void)) {
let cancellable = self.loginUser(user: user, pass: pass)
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
print("Handle error: \(error)")
case .finished:
break
}

}) { (result) in
completion(true)
self.accessToken = result.accessToken
self.refreshToken = result.refreshToken
UserDefaults.standard.set(self.accessToken, forKey: "AccessToken")
UserDefaults.standard.set(self.refreshToken, forKey: "RefreshToken")
}
cancellables.insert(cancellable)
}
}

如何显示警报?谢谢大家。

最佳答案

如果我正确理解您的流程,则问题出在登录逻辑中

let cancellable = self.loginUser(user: user, pass: pass)
.receive(on: DispatchQueue.main) // << add also this one !!
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
print("Handle error: \(error)")
completion(false) // << here !!
case .finished:
break
}

}) { (result) in
self.accessToken = result.accessToken
self.refreshToken = result.refreshToken
UserDefaults.standard.set(self.accessToken, forKey: "AccessToken")
UserDefaults.standard.set(self.refreshToken, forKey: "RefreshToken")
completion(true) // obviously should be called here !!
// and if result is provided always, ie. for
// failed login as well, then conditional
// completion should be called.
}

关于swift - SwiftUI MVVM如何在功能后显示警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65913214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com