swift登录与php

时间:2017-01-09 10:56:33

标签: php ios json swift xcode

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

Error Domain = NSCocoaErrorDomain Code = 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);

 ?>

1 个答案:

答案 0 :(得分:0)

使用此

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