ios - 使用json以快速登录形式从mysql获取登录数据

标签 ios swift

我是 swift 的新手。我开发了一个登录表单来验证来自 mysql 数据库的数据,为此我使用了 json 和 swift 代码。但是我的代码中存在一个问题,在我单击提交按钮时提供了登录详细信息之后。它显示了凭据无效的警报 View ,即使在提供了正确的凭据之后也是如此。我附上了下面的代码。如果有人可以帮助我,请帮助我

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()

        }





        }


}

最佳答案

你的问题在那里

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()

    }





     }
}

Check Json Response

关于ios - 使用json以快速登录形式从mysql获取登录数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50748949/

相关文章:

ios - 设置 MFMailComposeViewController (Objective-C) 时为 "Null passed to a callee that requires a non-null argument"

ios - 在 animateAlongsideTransition block 内的 UIImage 上进行交叉溶解

ios - 将 ImageView 放入 Collection View 单元格导致 IBTool 发出警告

iphone - 是否可以使用 ABPersonViewController 或 ABUknownPersonViewController 来显示联系信息?

ios - 从 double 小数中删除点并将小数值保留在整数中

iOS Facebook 快速登录

ios - 如何更新一个 xcode 实例?

ios - 按日期将值分组到数组中 - 无法从 Obj-C 桥接

swift - 如何以编程方式从 NSGlobalDomain 中删除首选项?

swift - 滑动动画以删除 UICollectionView 中的 Cell - Swift 2.0