简体   繁体   English

如何在 swift 5 中使用 alamofire 对登录到我的 iOS 应用程序的用户进行身份验证?

[英]How would I authentication users logging in to my iOS app with alamofire in swift 5?

I thought I finished my login system but it turned out I could write random letters and to be able to proceed to my tab bar controller.我以为我完成了我的登录系统,但事实证明我可以写随机字母并能够继续到我的标签栏 controller。 The information didn't authenticate.信息未通过验证。 This is my first app and I'm not sure where to start.这是我的第一个应用程序,我不知道从哪里开始。 Any help on this problem?对这个问题有任何帮助吗?

Here is my login.php code:这是我的登录名。php 代码:

<?php

//Step 1 Check variables passing to this file via POST
$username = htmlentities($_REQUEST["username"]);
$password = htmlentities($_REQUEST["password"]);

if (empty($username) || empty($password)) {
  $returnArray["status"] = "400";
  $returnArray["message"] = "Missing required information";
  echo json_encode($returnArray);
  return;
}

//Step 2. Build connection
//Secure way to build conn
$file = parse_ini_file("../../../iHertzmusic.ini");

// store in php var inf from ini var
$host = trim($file["dbhost"]);
$user = trim($file["dbuser"]);
$pass = trim($file["dbpass"]);
$name = trim($file["dbname"]);

// include access.php to call func from access.php file
require ("secure/access.php");
$access = new access($host, $user, $pass, $name);
$access->connect();

//Step 3. Get user information
//Assign result of execution of getUser to $user var
$user = $access->getUser($username);

//if we did not get any user information
if (empty($user)) {
    $returnArray["statusCode"] = "403";
    $returnArray["message"] = "User is not found";
    echo json_encode($returnArray);
    return;
}

//Step 4. Check validity of entered password
//get password and salt from db
$secured_password = $user["password"];
$salt = $user["salt"];

// check do passwords match: from db & entered one
if ($secured_password == sha1($password . $salt)) {
    $returnArray["statusCode"] = "200";
    $returnArray["message"] = "Logged in successfully";
    $returnArray["id"] = $user["id"];
    $returnArray["username"] = $user["username"];
    $returnArray["email"] = $user["email"];
    $returnArray["fullname"] = $user["fullname"];
} else {
    $returnArray["statusCode"] = "403"; //changed
    $returnArray["message"] = "passwords do not match";
  }

//STEP 5. Close connection
$access->disconnect();

//STEP 6. Throw back all infomation to users
echo json_encode($returnArray);



 ?>

Here is my.swift code这是我的.swift 代码

@IBAction func loginTapped(_ sender: Any) {

        // If no text entered
        if usernameTextfield.text!.isEmpty || passwordTextField.text!.isEmpty {

            //send message if fields are not filled
            print("User name \(String(describing: usernameTextfield)) or password \(String(describing: passwordTextField)) is empty")
            self.errorLabel.alpha = 1
            return
        } else {

            //Shortcuts
            let username = usernameTextfield.text
            let password = passwordTextField.text

            //send request to sql db
            let url = "http://10.0.0.157/iHertzmusic/login.php"

            let parameters: Parameters=[
             "username":usernameTextfield.text!,
             "password":passwordTextField.text!
            ]

            AF.request(url, method: .post, parameters: parameters as Parameters, encoding:
            URLEncoding.default).validate().response { (response) in

                    switch response.result {
                         case .success:
                         //sign in
                         let tabVC =
                         self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.TabBarController) as? UITabBarController
                         self.view.window?.rootViewController = tabVC
                         self.view.window?.makeKeyAndVisible()

                         case .failure(let error):
                         // Couldn't sign in
                            self.errorLabel.text = error.localizedDescription
                         self.errorLabel.alpha = 1
                    }
                  }

Based on the answer to What is the use of the validate() method in Alamofire.request?基于对 Alamofire.request 中 validate() 方法的用途是什么的回答 :

It would appear that the issue is due to the fact that you are returning the statusCode in the field status and are using a String and not an Int .看来问题是由于您在字段status中返回statusCode并且使用的是String而不是Int

Try changing尝试改变

$returnArray["status"] = "403";

to:至:

$returnArray["statusCode"] = 403;

and

$returnArray["status"] = "200";

to:至:

$returnArray["statusCode"] = 200;

If your php code returns success, you should save some data into app like如果您的 php 代码返回成功,您应该将一些数据保存到应用程序中,例如

UserDefaults.standard.set(true, forKey: "isLoggedIn")

and then in your appdelegate you should check this value然后在你的 appdelegate 中你应该检查这个值

let isLoggedIn = UserDefaults.standard.bool(forKey: "isLoggedIn")

if isLoggedIn {
    // push main view cont
} else {
    //not logged in show login view 
} 

you may need additional data like user info and want to save object see您可能需要其他数据,例如用户信息,并希望保存 object 参见

Save custom objects into NSUserDefaults 将自定义对象保存到 NSUserDefaults

this is just for swift code didn't check your php api is correcty written这仅适用于 swift 代码未检查您的 php api 是否正确写入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在我的网站上显示用户数据库中的个人资料图片? - how would i show a profile picture on my website from my database from the users? 我如何将参数传递给Swift / iOS的php文件中的类函数? - How would I pass a parameter into a class function in a php file from Swift/iOS? 登录后如何根据用户在 laravel 中的角色重定向用户 - How do I redirect users after logging in based on their role in laravel 如何记录用户登录和注销的日志? - How can I keep a log of users logging in and out? 登录后如何让用户输入用户名? - How do I get users to enter their username after logging in? 我有两种类型的用户 - 用户和管理员。 我想包括一个会话检查,以检查该人是以用户身份登录还是以管理员身份登录。 - I have two types of users - User and Admin. I would like to include a session check, to check if the person is logging on as a user or as an admin. 移动应用程序:用户写入数据库如何确定他们可以(身份验证)? - Mobile App: users writing to DB how to be sure they can(authentication)? 需要您的帮助,IOS Swift将数据发布到Json Alamofire - Need your help, IOS Swift Post data to Json Alamofire 如何允许 iOS 用户通过我网站上的 html 输入字段上传文档? - How do I allow iOS users to upload a document via an html input field on my website? 通过MySQLi登录iOS应用 - iOS app logging in via MySQLi
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM