php - 快速登录 POST 连接 php

标签 php ios json swift xcode

我是 Swift 新手,我正在尝试在后端使用 PHP 创建安全登录。但是我在某个地方出错了,即使我不提供登录凭据并在控制台中收到以下错误,我的 View Controller 仍会转到下一个 View Controller : 请帮忙!!

错误域 = NSCocoaErrorDomain 代码 = 3840 “JSON 文本未以数组或对象开头,并且未设置允许片段的选项。” UserInfo={NSDebugDescription=JSON 文本未以数组或对象开头,并且未设置允许片段的选项

我的代码:

@IBAction func loginAuthentication(sender: UIButton) {

            //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
            let myUrl = NSURL(string: "my url");

            var request = NSMutableURLRequest(URL:myUrl!)

            request.HTTPMethod = "POST"// Compose a query string

            let postString = "username = \( NameTextField.text!) & password = \( passwortTextField.text!) ";

            request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)



            let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data , response , error in

                if error != nil
                                {
                                let alert = UIAlertView()
                                alert.title = "Login Failed!"
                                alert.message = "Error: \(error)"
                                alert.delegate = self
                                alert.addButtonWithTitle("OK")
                                alert.show()
                                return
                                }

        // You can print out response object
        print("*****response = \(response)")

        let responseString = NSString(data: data! , encoding: NSUTF8StringEncoding )

                if ((responseString?.containsString("")) != nil) {
                    print("incorrect - try again")

                    let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: .Alert)
                    let yesAction = UIAlertAction(title: "Nochmalversuchen", style: .Default) { (action) -> Void in

                    }


            // Add Actions
            alert.addAction(yesAction)


            // Present Alert Controller
            self.presentViewController(alert, animated: true, completion: nil)
                }

                else {
                      print("correct good")

                      let storyboard = UIStoryboard(name: "Main", bundle: nil)
                      let controller = storyboard.instantiateViewControllerWithIdentifier("toPflegerProfile")
                      self.presentViewController(controller, animated: true, completion: nil)
                    }

            print("*****response data  = \(responseString)")

            do {
            //create json object from data
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? [String: Any] {

                    if let email = json["UserName"] as? String,
                    let password = json["passowrd"] as? String {

                    print ("Found User id:  called \(email)")
                    }
                }

            } catch let error {
            print(error)
        }

    }
    task.resume()
}

PHP 代码:

 <?php

  require_once 'db.php';
  $conn = connect();

  if($conn)
   {


     if (isset($_GET['loginuser']))
      {
       //Getting post values
       require_once 'getuserdata.php';
       //1.Check if user is looged in
       $loggedin = checkuserloggedin($username, $conn);
       if ($loggedin)
         {
         $response['error']=true;
         $response['message']='User is already logged in!';
        }
    else
     {
      //2.If not, insert pfleger
       //Inserting log in values
      if (insertuserdata($name,$username, $password, $gps, $logintime,    $conn)) 
       {
        $response['error']=false;
        $response['message']='Log Data added successfully';
      }
      else
      {
        $response['error']=true;
        $response['message']='Could not add log in data';
      }
    }

    }

  else
     {
      $response['error']=true;
      $response['message']='You are not authorized';
      }
 echo json_encode($response);

 ?>

最佳答案

用这个

   var request = URLRequest(url: URL(string: “url”)!)
   request.httpMethod = "POST"
   let userName = self.emailTextField.text!
   let password = self.passtextField.text!

   let postString = NSString(format: "emailId=%@&password=%action=%@",userName, password,”action name”)
   request.httpBody = postString.data(using: String.Encoding.utf8.rawValue)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        do {

            let jsonResults : NSDictionary = try JSONSerialization.jsonObject(with: data, options: [])as! NSDictionary
            print("login json is ---%@",jsonResults)

            let str = jsonResults.object(forKey: "status")as! String
            if (str == "Success")
            {
            let newdic:NSDictionary = jsonResults.object(forKey: "response") as! NSDictionary

        } catch {

            // failure
                print("Fetch failed: \((error as NSError).localizedDescription)")
            }
            }
            task.resume()

关于php - 快速登录 POST 连接 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41546424/

相关文章:

iOS RTL - 在 RTL 字符串中不正确地显示英语

javascript - 使用 split() 循环遍历数组,以逗号分隔项目

php - 在 Eloquent 中按自定义顺序对集合进行排序

ios - NSCalendar currentCalendar 在 cocoapod 内部调用时返回 nil?

php - NULL MySQL 到 PHP PDO

iOS 应用程序 AdColony 框架错误的视频方向

json - 如何简化命令行中的 aws DynamoDB 查询 JSON 输出?

json - 注册。带有jqgrid的json中的日期格式问题

php - 如何使用php获取我的网站访问者的IP地址

javascript - 使用 Firebase Storage 和 Dropzone 通过 JavaScript 上传