Ios 如果用户的信息不正确,如何阻止用户通过登录页面
在我的IOS应用程序中,我想向试图使用错误凭据登录的用户发送一条消息,并通过弹出窗口通知他们。目前,我的数据库可以识别登录错误,但我的swift代码直到关闭登录页面并进入应用程序后才看到错误情况 访问数据库的flask/python代码如下所示:Ios 如果用户的信息不正确,如何阻止用户通过登录页面,ios,mysql,swift,flask,swiftui,Ios,Mysql,Swift,Flask,Swiftui,在我的IOS应用程序中,我想向试图使用错误凭据登录的用户发送一条消息,并通过弹出窗口通知他们。目前,我的数据库可以识别登录错误,但我的swift代码直到关闭登录页面并进入应用程序后才看到错误情况 访问数据库的flask/python代码如下所示: @app.route('/login', methods=['GET', 'POST']) def login(): mydb = mysql.connector.connect(host="localhost", user="root", p
@app.route('/login', methods=['GET', 'POST'])
def login():
mydb = mysql.connector.connect(host="localhost", user="root", passwd="Pass", database = "events")
if request.method == 'POST':
mycursor = mydb.cursor()
username = request.form['username']
password = request.form['password']
mycursor.execute('SELECT* FROM accounts WHERE username = %s AND password = %s', (username, password,))
account = mycursor.fetchone()
if account:
try:
mydb.commit()
mydb.close()
except e:
# Rollback in case there is any error
print("Error: ", e)
mydb.rollback()
return make_response("Success!", 200)
else:
return make_response("username/password combination dne", 500)
@State private var didLogin: Bool = false
if didLogin {
ShowSomeViewAfterLogin()
} else {
ShowLogin()
}
与我的应用程序内的数据库联系的swiftui代码如下所示:
struct LogInView: View {
@State var username: String = ""
@State var password: String = ""
@State var email: String = "test@gmail.com"
@Binding var didLogin: Bool
@Binding var needsAccount: Bool
@State var errorString: String = ""
func send(_ sender: Any, completion: @escaping (String) -> Void) {
let request = NSMutableURLRequest(url: NSURL(string: "http://localhost/login")! as URL)
request.httpMethod = "POST"
self.username = "\(self.username)"
self.password = "\(self.password)"
self.email = "\(self.email)"
let postString = "username=\(self.username)&password=\(self.password)&c=\(self.email)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
if error != nil {
print("error=\(String(describing: error))")
//put variable that triggers error try again view here
self.didLogin = false
self.errorString = String(describing: error)
completion(self.errorString)
return
}else{
self.didLogin = true
completion(String(describing: error))
}
print("response = \(String(describing: response))")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(String(describing: responseString))")
if let httpResponse = response as? HTTPURLResponse {
self.errorString = String(httpResponse.statusCode)
}
}
task.resume()
}
var body: some View {
VStack{
Spacer()
WelcomeText()
UserImage()
TextField("Username", text: $username)
.padding()
.background(Color(.lightGray))
.cornerRadius(5.0)
.padding(.bottom, 20)
SecureField("Password", text: $password)
.padding()
.background(Color(.lightGray))
.cornerRadius(5.0)
.padding(.bottom, 20)
Button(action: {
self.send((Any).self){ array in
self.errorString = array
}/*
if self.errorString == "500"{
self.didLogin = false
}
else{
self.didLogin = true
}
}*/
},
label: {Text("LOGIN")
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(width: 220, height: 60)
.background(Color.orange)
.cornerRadius(15.0)})
.shadow(radius: 5)
.padding(.bottom, 10)
Button(action: {
self.needsAccount = true
}, label: {Text("Not a member yet? Sign up here")})
Spacer()
}.padding().background(Color.white).edgesIgnoringSafeArea(.all)
}
}
ContentView:
import SwiftUI
import Mapbox
import CoreLocation
struct ContentView: View {
@ObservedObject var annotationsVM: AnnotationsVM //= AnnotationsVM()
@ObservedObject var VModel: ViewModel //= ViewModel()
@ObservedObject var locationManager: LocationManager //= LocationManager()
@ObservedObject var data: DataFetcher
// @ObservedObject var mapViewCoordinator = MapViewCoordinator()
init() {
let vm = ViewModel()
VModel = vm
annotationsVM = AnnotationsVM(VModel: vm)
locationManager = LocationManager()
data = DataFetcher()
}
var userLatitude: CLLocationDegrees {
return (locationManager.lastLocation?.latitude ?? 0)
}
var userLongitude: CLLocationDegrees {
return (locationManager.lastLocation?.longitude ?? 0)
}
var lat: Double {
return (VModel.lat ?? 0)
}
var long: Double {
return (VModel.lon ?? 0)
}
var Userlat: Double {
return (VModel.userLatitude)
}
var Userlon: Double {
return (VModel.userLongitude)
}
//@State var searchedLocation: String = ""
@State private var annotationSelected: Bool = false
@State private var renderingMap: Bool = true
@State private var searchedText: String = ""
@State private var showResults: Bool = false
@State private var events: [eventdata] = []
@State private var showMoreDetails: Bool = false
@State private var didLogin: Bool = false
@State private var needsAccount: Bool = false
@State private var selectedAnnotation: MGLAnnotation? = nil
var body: some View {
VStack{
ZStack(alignment: Alignment(horizontal: .leading, vertical: .top)){
MapView(annotationSelected: $annotationSelected, renderingMap: $renderingMap, visited: $annotationsVM.visited, showMoreDetails: $showMoreDetails, selectedAnnotation: $selectedAnnotation, VModel: VModel, locationManager: locationManager, aVM: annotationsVM, data: data, annos: $annotationsVM.annos)
.edgesIgnoringSafeArea(.all)
if showResults == true && searchedText.count >= 1 {
Text("").frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(Color.white).edgesIgnoringSafeArea(.all)
//this is pretty ghetto but whatever
}
VStack{
HStack(alignment: .top){
if showResults == false {
SettingsButton()
}
Spacer()
SearchBar(annotation: annotationsVM, VModel: VModel, searchedText: $searchedText, showResults: $showResults, showMoreDetails: $showMoreDetails)
// SearchBar(annotation: annotationsVM) { sender in
// self.searchedLocation = sender.searchText.text
// }
Spacer()
if showResults == false {
MessageButton()
}
}.padding()
//Update Annotation Button
// Button (action: {
// let delayInSeconds = 1.5
// DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
// self.annotationsVM.addNextAnnotation(address: "22 Sunset Ave, East Quogue, NY")
//
// print("\(self.annotationsVM.annos)")
// print("User Coords: \(self.VModel.userLatitude), \(self.VModel.userLongitude)")
// }
// }, label: {Text("Press to update annotation")})
if showResults == true && searchedText.count >= 1 {
SearchResults(VModel: VModel, annotation: annotationsVM, showResults: $showResults, searchedText: $searchedText)
}
Spacer()
HStack(alignment: .bottom) {
if renderingMap {
Text("The Map is Rendering...")
}
}
//Side Note: If the Create Event Button is pressed, the currently selected annotation is unselected, so that'll need to be fixed
HStack(alignment: .bottom) {
if annotationSelected {
CreateEventButton(annotation: annotationsVM, annotationSelected: $annotationSelected)
}
}.padding()
}
VStack {
Spacer()
HStack {
Spacer()
if annotationsVM.annotationPlacementFailed == true {
AnnotationPlacementErrorView(annotationPlacementFailed: $annotationsVM.annotationPlacementFailed, annotation: annotationsVM, searchedText: $searchedText)
}
Spacer()
}
Spacer()
}
VStack {
Spacer()
HStack{
Spacer()
if self.showMoreDetails == true {
MoreDetailsView(searchedText: $searchedText, showMoreDetails: $showMoreDetails, selectedAnnotation: $selectedAnnotation)
//Instead of passing in searchedText, we need to pass in the mapView...idk how though
}
Spacer()
}
Spacer()
}
if self.didLogin == false {
LogInView(didLogin: $didLogin, needsAccount: $needsAccount)
}
if self.needsAccount == true {
SignUpView(didLogin: $didLogin, needsAccount: $needsAccount)
}
}
}
}
}
我不确定这是数据库//服务器问题还是swiftui/httpresponse问题。非常感谢任何见解它如何关闭登录页面?假设您使用didLogin进行检查,您应该将默认的
didLogin
设置为false。因此,用户在didLogin=true
之前不会登录,这意味着它将等待您收到http请求的响应。大概是这样的:
@app.route('/login', methods=['GET', 'POST'])
def login():
mydb = mysql.connector.connect(host="localhost", user="root", passwd="Pass", database = "events")
if request.method == 'POST':
mycursor = mydb.cursor()
username = request.form['username']
password = request.form['password']
mycursor.execute('SELECT* FROM accounts WHERE username = %s AND password = %s', (username, password,))
account = mycursor.fetchone()
if account:
try:
mydb.commit()
mydb.close()
except e:
# Rollback in case there is any error
print("Error: ", e)
mydb.rollback()
return make_response("Success!", 200)
else:
return make_response("username/password combination dne", 500)
@State private var didLogin: Bool = false
if didLogin {
ShowSomeViewAfterLogin()
} else {
ShowLogin()
}
它如何关闭登录页面?假设您使用didLogin进行检查,您应该将默认的
didLogin
设置为false。因此,用户在didLogin=true
之前不会登录,这意味着它将等待您收到http请求的响应。大概是这样的:
@app.route('/login', methods=['GET', 'POST'])
def login():
mydb = mysql.connector.connect(host="localhost", user="root", passwd="Pass", database = "events")
if request.method == 'POST':
mycursor = mydb.cursor()
username = request.form['username']
password = request.form['password']
mycursor.execute('SELECT* FROM accounts WHERE username = %s AND password = %s', (username, password,))
account = mycursor.fetchone()
if account:
try:
mydb.commit()
mydb.close()
except e:
# Rollback in case there is any error
print("Error: ", e)
mydb.rollback()
return make_response("Success!", 200)
else:
return make_response("username/password combination dne", 500)
@State private var didLogin: Bool = false
if didLogin {
ShowSomeViewAfterLogin()
} else {
ShowLogin()
}
didLogin在内容视图中初始化为false,然后传递到登录视图。我不知道当一个登录错误发生时,didLogin是如何变成真的。这很奇怪,有几个问题。你的
完成
是做什么的?您可以将ContentView代码添加到问题中吗?完成只是更新ContentView上的errorString变量asynchronouslybit。如果self.didLogin==false,为什么没有其他块?这就是所有应用程序视图应该位于的位置。没有其他块,因为我只希望在用户未登录时显示视图(didLogin==false)。如果didLogin==true,则视图应该消失,这确实发生了。问题是,即使我输入了错误的登录凭据并从服务器接收到错误,didLogin也会被设置为true,即使它不应该是beddLogin。在内容视图中,didLogin被初始化为false,然后传递到登录视图中。我不知道当一个登录错误发生时,didLogin是如何变成真的。这很奇怪,有几个问题。你的完成
是做什么的?您可以将ContentView代码添加到问题中吗?完成只是更新ContentView上的errorString变量asynchronouslybit。如果self.didLogin==false,为什么没有其他块?这就是所有应用程序视图应该位于的位置。没有其他块,因为我只希望在用户未登录时显示视图(didLogin==false)。如果didLogin==true,则视图应该消失,这确实发生了。问题是,即使我输入了错误的登录凭据并从服务器接收到错误,didLogin也被设置为true,即使它不应该是true