我是swift的新手。我已经开发了一个登录表单来验证来自mysql数据库的数据,为此我使用了json和swift代码。但是,在我单击提交按钮后提供登录详细信息后,我的代码中存在一个问题。即使提供了正确的凭据,它也会显示凭据无效的警报视图。我已附上以下代码。如果有人可以帮助我
class ViewController: UIViewController {
@IBOutlet weak var PASSWORD: UITextField!
@IBOutlet weak var USERNAME: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func submitbtn(_ sender: Any) {
let username: NSString = self.USERNAME.text! as NSString
let password: NSString = self.PASSWORD.text! as NSString
if username.isEqual(to: "") || password.isEqual(to: ""){
let myAlert = UIAlertController(title: "Alert", message:"All fields are required to fill in", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
// return
}
else
{
let post:NSString = "UserName\(username)&PassWord\(password)" as NSString
NSLog("PostData : %d", post)
let url = "http://demo.talentclouds.in/API/LoginHandler.asmx/Login?username=admin@penn.in&password=123"
let postData:NSData = post.data(using: String.Encoding.ascii.rawValue)! as NSData
let postLength:NSString = String ( postData.length ) as NSString
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "POST"
request.httpBody = postData as Data
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoder", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
// let responseError:NSError?
// let response:URLResponse?
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
DispatchQueue.main.async {
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
//parsing the response
do {
//converting resonse to NSDictionary
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let username = parseJSON["username"] as? String
if(username != nil)
{
UserDefaults.standard.set(parseJSON["username"], forKey: "username")
UserDefaults.standard.set(parseJSON["password"], forKey: "password")
UserDefaults.standard.synchronize()
// let username : NSInteger = json?.value(forKey: username as String)as! NSInteger
// NSLog("Success : %ld ", username)
// if (username != nil)
// {
print("Login OK")
}
else{
print("Login Failed")
let alert = UIAlertController(title: "Invalid", message: "Invalid Credentials", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
catch {
print("Login Failed")
let alert = UIAlertController(title: "Error", message: "Please check your internet connection", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
})
//executing the task
task.resume()
}
}
}
答案 0 :(得分:0)
你的问题
let username = parseJSON["username"] as? String
应首先阅读profile
字典
if let profile = parseJSON["Profile"] as? [String:Any],
let username = profile["username"] as? String
此处完整代码:
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
DispatchQueue.main.async {
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
//parsing the response
do {
//converting resonse to NSDictionary
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
if let profile = parseJSON["Profile"] as? [String:Any],
let username = profile["username"] as? String
{
UserDefaults.standard.set(parseJSON["username"], forKey: "username")
UserDefaults.standard.set(parseJSON["password"], forKey: "password")
UserDefaults.standard.synchronize()
// let username : NSInteger = json?.value(forKey: username as String)as! NSInteger
// NSLog("Success : %ld ", username)
// if (username != nil)
// {
print("Login OK")
}
else{
print("Login Failed")
let alert = UIAlertController(title: "Invalid", message: "Invalid Credentials", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
catch {
print("Login Failed")
let alert = UIAlertController(title: "Error", message: "Please check your internet connection", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
})
//executing the task
task.resume()
}
}
}