iOS – User registration with PHP/MySQL and LoginKit UI
In this tutorial we’ll build a simple and effective user registration system for iOS in Swift. Which we are going to complement by the coming tutorials on iOS authentication through 3d-parties like Facebook Swift SDK and the Goodreads API.
What we’ll build
First we are creating our services in php to add and manage users in a MySQL database. For that you might need a webserver stack. We’ll use MAMP that offers the Apache, MySQL and PHP stack . You’ll also need a tool like Postman to test your API .
Then we’ll use the LoginKit UI library for Swift to be build the following user registration uis. This step is optional as you can create your own simple user interface.
1 – Building a simple user management API
The most basic way to build a consumable user management API with php is simply to add a connect.php , register.php and login.php scripts under on local server with the following code:
Note: this example is made just for learning and you can not rely on using it in a real application. Do look for a more sophisticated and secure php registration example if you tend to host your services and publish to the app store.
connect.php
<?php define('HOST','localhost'); define('USER','root'); define('PASS','root'); define('DB','authsampledb'); $con = mysqli_connect(HOST,USER,PASS,DB) or die('unable to connect to db'); ?>
register.php
<? if($_SERVER['REQUEST_METHOD']=='GET') { $response = array(); $email = $_GET['email']; $password = md5($_GET['password']); $username = $_GET['username']; require_once('connect.php'); $sql = "INSERT INTO users (email,password,username) VALUES('$email','$password','$username')"; if(mysqli_query($con,$sql)) { $response["value"] = 1; echo json_encode($response); } else { $response["value"] = 0; echo json_encode($response); } mysqli_close($con); } else { $response["value"] = -1; echo json_encode($response); } ?>
login.php
<?php if($_SERVER['REQUEST_METHOD']=='GET') { $response = array(); $email = $_GET['email']; $password = md5($_GET['password']); require_once('connect.php'); $sql1 = "SELECT * FROM users WHERE email ='$email'"; $checkemail = mysqli_fetch_array(mysqli_query($con,$sql1)); $sql2 = "SELECT * FROM users WHERE password ='$password'"; $checkpassword = mysqli_fetch_array(mysqli_query($con,$sql2)); if(isset($checkemail)){ $response["value"] = 1; $response["message"] = "correct email"; echo json_encode($response); }else { $response["value"] = 0; $response["message"] = "oops! this email is not registered"; echo json_encode($response); } if(isset($checkpassword)){ $response["value"] = 1; $response["message"] = "correct passs"; echo json_encode($response); }else { $response["value"] = 0; $response["message"] = "oops! wrong password"; echo json_encode($response); } mysqli_close($con); } else { $response["value"] = 0; $response["message"] = "conexion failed2!"; echo json_encode($response); }?>
You can test this simple api out on your browser or using Postman as follows :
2 – Setting up the UIs
First we’ll need to add ILoginKit to our pod file as follows:
use_frameworks! target 'AuthSample_Example' do pod 'ILLoginKit' pod 'Alamofire' end
Then we’ll be subclassing the LoginCoordinator class of the API to define a staring point for our app as follows :
import UIKit import ILLoginKit class ViewController: UIViewController { var hasShownLogin = false lazy var loginCoordinator: LoginCoordinator = { return LoginCoordinator(rootViewController: self) }() override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { guard !hasShownLogin else { return } hasShownLogin = true loginCoordinator.start() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: LoginViewControllerDelegate { func didSelectLogin(_ viewController: UIViewController, email: String, password: String) { print("DID SELECT LOGIN; EMAIL = \(email); PASSWORD = \(password)") } func didSelectForgotPassword(_ viewController: UIViewController) { print("LOGIN DID SELECT FORGOT PASSWORD") } func loginDidSelectBack(_ viewController: UIViewController) { print("LOGIN DID SELECT BACK") } }
In the LoginCoordinator class we’ll need to add the following to configure our login/signup uis:
class LoginCoordinator: ILLoginKit.LoginCoordinator { override func start(animated: Bool = true) { configureAppearance() // Configure before calling super super.start(animated: animated) } override func finish(animated: Bool = true) { super.finish(animated: animated) } func configureAppearance() { configuration = DefaultConfiguration(backgroundImage: #imageLiteral(resourceName: "Background"), tintColor: UIColor(red: 52.0/255.0, green: 152.0/255.0, blue: 219.0/255.0, alpha: 1), errorTintColor: UIColor(red: 253.0/255.0, green: 227.0/255.0, blue: 167.0/255.0, alpha: 1), signupButtonText: "Create Account", loginButtonText: "Sign In", facebookButtonText: "Login with Facebook", forgotPasswordButtonText: "Forgot password?", recoverPasswordButtonText: "Recover", emailPlaceholder: "E-Mail", passwordPlaceholder: "Password!", repeatPasswordPlaceholder: "Confirm password!", namePlaceholder: "Name", shouldShowSignupButton: true, shouldShowLoginButton: true, shouldShowFacebookButton: true, shouldShowForgotPassword: true) } }
And we’ll override the login() and signup() functions of the API which gets called on user’s click on login or signup buttons as follows :
override func signup(name: String, email: String, password: String){ //Handle user signup via your API } override func login(email: String, password: String){ //Handle user login via your API }
3 – Consuming our API with Alamofire
So in the signup method we’ll simply use Alamofire to perform network calls to our API and read the value key from returned json response to redirect the user depending on its 0 or 1 value :
user registration:
override func signup(name: String, email: String, password: String){ let parameters: Parameters=[ "email":email, "password":password, "username":name] Alamofire.request("http://102.157.226.95:8888/authSample/register.php", method: .get, parameters: parameters).responseJSON { response in if let result = response.result.value { let jsonData = result as! NSDictionary let val = jsonData.value(forKey: "value") as! Int64 print("RES:\(val)") if(val==0){ print("fail") self.didSelectSignup(self.viewController, email:email, name:name, password:password) } else if(val==1){ print("succes") let alert = UIAlertController(title: "Registered !", message: "You havee been successfully registered!", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Take me to login", style: UIAlertActionStyle.cancel) { UIAlertAction in // super.didSelectLogin(self.visibleViewController()!, email: "", password: "") self.signupDidSelectBack(self.viewController) }) self.visibleViewController()!.present(alert, animated: true, completion: nil) } } }
user login:
override func login(email: String, password: String) { print("from login") let parameters: Parameters=[ "email":email, "password":password] Alamofire.request("http://102.157.226.95:8888/authSample/login.php", method: .get, parameters: parameters).responseJSON { response in if let error = response.result.error as? AFError { if case .responseValidationFailed(.unacceptableStatusCode(let code)) = error { print("ERROR:\(code)") } } let status = response.response?.statusCode print("STATUS \(status)") if let result = response.result.value { let jsonData = result as! NSDictionary let val = jsonData.value(forKey: "value") as! Int64 print("VALUE:\(val)") if(val==0){ print("fail") //self.didSelectSignup(self.viewController, email:email, name:"", password:password) } else if(val==1){ print("succes") self.visibleViewController()!.prepare(for: "navigateToHome", sender:self.visibleViewController()!) } } }
That’s all it takes to build a simple user registration system using the LoginKit UI library for ui and basic php services for backend. You can check out the source code for this example in here.
Very Nice Thanks For the Explanation.