[:en]Swift+ PHP User login check[:]

[:en]The login info depends on your own server:


connect_error) {

    die("Connection failed: " . $con->connect_error);

}

?>


connect_error) {

    die("Connection failed: " . $con->connect_error);

}

// Change character set to utf8

mysqli_set_charset($con,"utf8");

$user = $_POST["user"];

$sql1 = "SELECT name FROM customer

       WHERE name = '$user'";

          

$check1 = mysqli_fetch_array(mysqli_query($con,$sql1));

if(isset($check1)){

  echo "already";

} else {

  echo "ok";

}

if ($con->query($sql) === TRUE) {

    

} else {

    

}

$con->close();

?>


//
//  LoginViewController.swift
//
//  Created by Joshua on 16/7/19.
//  Copyright © 2019 Joshua. All rights reserved.
//

import Foundation
import UIKit
import QuartzCore




var resultlogin: String = ""

// Set up a task to upload or download data from the server.
var task = URLSessionDataTask()





class LoginViewController: UIViewController , UITextFieldDelegate {
    
    
    
    
    
    @IBOutlet weak var username: UITextField!
    @IBOutlet weak var loginButton: UIButton!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //Please check https://www.youtube.com/watch?v=rQ6jy4FRQGc to fix Transport Security Error
    }
    
    
    
    
    // To make a button to login.
    @IBAction func LoginBut(_ sender: AnyObject) {
        
        checkpassword()
        
    }
    
    
    
    // Login
    func checkpassword() {
        
// To make the keyboard disappear. See my video at https://www.youtube.com/watch?v=9MdwF4KSh3E&t=143s .
        self.username.resignFirstResponder()
        
        if let user1 = username.text {
            // To remove any empty space from textbox.
            let user1B = user1.replacingOccurrences(of: " ", with: "")
            
            
            // Check for empty fields
            if(user1B.isEmpty)
            {
                // They will give a message saying "Your name can't be empty."
                AlertMessage("Your name can't be empty.");
                return;
            } else {
                onlinecheckin()
            }
        }
    }
    //To make an online checking.
    func onlinecheckin(){
        if let user1 = username.text {
            // To trim the characters to remove the empty space
            let username = user1.trimmingCharacters(in: CharacterSet.whitespaces)
            
            
            //Send user data to server side
            let myUrl = URL(string: "http://inventlinks.com/youtube/check.php")
            let request = NSMutableURLRequest(url: myUrl!);
            request.httpMethod = "POST" // Use a "POST" method for Swift, "GET" for Objective C
            let postString = "user=\(username)" //To upload any text at the server.
            request.httpBody = postString.data(using: String.Encoding.utf8)
            
            task = URLSession.shared.dataTask(with: request as URLRequest) {                data, response, error in
                
                // To print response from the server. If code is 200 which means connection with the server is established.
                print("response online checking =\(String(describing: response))")

                if error != nil { //If error is not equal to nothing, which means there is an error.
                    task.cancel() // To cancel uploading the task.
                    self.AlertMessage("Error. Please press Login button again.");
                    print("error=\(String(describing: error))")
                    return
                }
                
                // Print out downloaded data.
                if let datadownload = data {
                    resultlogin = NSString(data: datadownload, encoding: String.Encoding.utf8.rawValue)!.replacingOccurrences(of: " ", with: "");
                    print("result of online checking:\(resultlogin)")
                    
                }
                // After getting the downloaded data, what we are going to do the following:
                DispatchQueue.main.async(execute: { () -> Void in
                 if resultlogin.contains("correct") {

                        self.AlertMessage("Sucessful!");
                     // you can perform other tasks as well.
                    
                    } else {
                        self.AlertMessage("This name has already been taken.");
                        
                    }
                })
            }
            task.resume()
        }
    }
    
    
    
    
    // to make the keyboard disappear
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }
    
    
    
    func AlertMessage(_ userMessage:String)
    {
        let Alert = UIAlertController(title:"", message:userMessage, preferredStyle: UIAlertController.Style.alert);
        
        let okClick = UIAlertAction(title:"Ok", style:UIAlertAction.Style.default, handler:nil);
        
        Alert.addAction(okClick);
        self.present(Alert, animated:true, completion:nil);
    }
    
}







[:]

Print Friendly, PDF & Email
Scroll to Top