In this post we will see an iOS Registration Form Example. A user registration and login screen is a very essential thing in many application. Thats why I am posting this iOS Registration Form Example. In the next post we will see iOS Login Example.
I am going to use PHP and MySQL as application’s backend. And we will use Swift Programming in XCode. We already learnt about connecting iOS App to MySQL database, in one of the previous tutorials. You can check the tutorial from the below link.
Connecting iOS App to MySQL Database
In this post we will use the same concept but this time for networking operations I will be using Alamofire. If you don’t know what it is then don’t worry just keep reading.
Contents
iOS User Registration Video Tutorial
- You can also watch this video tutorial to know how to build this app.
Building Server Side Scripts and Database
Building Database
- First we need a database. So I have the following database.
- For creating the above Table you can use the following query.
-- tables -- Table: users CREATE TABLE users ( id int NOT NULL PRIMARY KEY AUTO_INCREMENT, username varchar(100) NOT NULL, password text NOT NULL, email varchar(100) NOT NULL, name varchar(100) NOT NULL, phone varchar(10) NOT NULL ); -- End of file.
- Executing the above query will create the following table.
Building Web Service
- Now we need a Web Service that will act as a medium of communication between our application and database. Again I am using very simple method to do this. But you can also check the recommended method of Building a REST API on this link.
Creating a PHP Project
- The first step is creating a new project. I am using PHP Storm, you can use any IDE you like or a normal source code editor like sublime or notepad++ will also be good enough.
- Now inside your project you have to create two directories named includes and v1. Inside includes create three php files Constants.php, DbConnect.php, DbOperation.php and inside v1 create register.php. (See the screenshot below for help).
Constants.php
- Open Constants.php and write the following code. The file is containing the required constants.
<?php /** * Created by PhpStorm. * User: Belal * Date: 04/02/17 * Time: 7:50 PM */ define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', 'localhost'); define('DB_NAME', 'simplifiedios'); define('USER_CREATED', 0); define('USER_ALREADY_EXIST', 1); define('USER_NOT_CREATED', 2);
DbConnect.php
- This file will connect to the database and will return a connection link.
<?php /** * Created by PhpStorm. * User: Belal * Date: 04/02/17 * Time: 7:51 PM */ class DbConnect { private $conn; function __construct() { } /** * Establishing database connection * @return database connection handler */ function connect() { require_once 'Constants.php'; // Connecting to mysql database $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); // Check for database connection error if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // returing connection resource return $this->conn; } }
DbOperation.php
- This file will handle all the database operations. Right now we have to only insert the user data to the table.
<?php /** * Created by PhpStorm. * User: Belal * Date: 04/02/17 * Time: 7:51 PM */ class DbOperation { private $conn; //Constructor function __construct() { require_once dirname(__FILE__) . '/Constants.php'; require_once dirname(__FILE__) . '/DbConnect.php'; // opening db connection $db = new DbConnect(); $this->conn = $db->connect(); } //Function to create a new user public function createUser($username, $pass, $email, $name, $phone) { if (!$this->isUserExist($username, $email, $phone)) { $password = md5($pass); $stmt = $this->conn->prepare("INSERT INTO users (username, password, email, name, phone) VALUES (?, ?, ?, ?, ?)"); $stmt->bind_param("sssss", $username, $password, $email, $name, $phone); if ($stmt->execute()) { return USER_CREATED; } else { return USER_NOT_CREATED; } } else { return USER_ALREADY_EXIST; } } private function isUserExist($username, $email, $phone) { $stmt = $this->conn->prepare("SELECT id FROM users WHERE username = ? OR email = ? OR phone = ?"); $stmt->bind_param("sss", $username, $email, $phone); $stmt->execute(); $stmt->store_result(); return $stmt->num_rows > 0; } }
register.php
- Now this is the main script where we will send the request to register a new user.
<?php /** * Created by PhpStorm. * User: Belal * Date: 04/02/17 * Time: 7:51 PM */ //importing required script require_once '../includes/DbOperation.php'; $response = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (!verifyRequiredParams(array('username', 'password', 'email', 'name', 'phone'))) { //getting values $username = $_POST['username']; $password = $_POST['password']; $email = $_POST['email']; $name = $_POST['name']; $phone = $_POST['phone']; //creating db operation object $db = new DbOperation(); //adding user to database $result = $db->createUser($username, $password, $email, $name, $phone); //making the response accordingly if ($result == USER_CREATED) { $response['error'] = false; $response['message'] = 'User created successfully'; } elseif ($result == USER_ALREADY_EXIST) { $response['error'] = true; $response['message'] = 'User already exist'; } elseif ($result == USER_NOT_CREATED) { $response['error'] = true; $response['message'] = 'Some error occurred'; } } else { $response['error'] = true; $response['message'] = 'Required parameters are missing'; } } else { $response['error'] = true; $response['message'] = 'Invalid request'; } //function to validate the required parameter in request function verifyRequiredParams($required_fields) { //Getting the request parameters $request_params = $_REQUEST; //Looping through all the parameters foreach ($required_fields as $field) { //if any requred parameter is missing if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) { //returning true; return true; } } return false; } echo json_encode($response);
Testing Web Service
- Now lets test it is working or not. You can use any REST Client extension I am using POSTMAN.
- As you can see it is working fine. Also check the database whether the values are inserted or not.
iOS Registration Form Example
- Now its time to start our XCode Project.
Creating a new XCode Project
- Create a Single View application.
- Now close the project as we need to Add Alamofire. For this we will use Cocoapods. If you don’t know about it check the Firebase iOS Tutorial where I have explained about cocoa pods in detail.
Adding Alamofire
- Open terminal and navigate to your Xcode Project Directory.
- Now right the following command.
pod init
- The above command will create a podfile inside your project folder. Open the file and replace the content with the following.
# Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'UserRegistrationExample' do use_frameworks! pod 'Alamofire', '~> 4.3' end
- Now come back to the terminal window and run the following command.
pod install
- This will install Alamofire to your project. Now just go inside your project folder and open the file ProjectName.xcworkspace.
Creating Interface
- In Main.storyboard create the following screen.
- As you can see we have 5 TextFields, a Button and a Label.
Connecting Views with Code
- Now connect all your views to your ViewController.swift file. I already explained it in previous tutorials. You can go the tutorial from these links.
Xcode Text Field Tutorial for iOS Application using Swift
Xcode Button Tutorial for iPhone using Swift in Xcode 7
Adding User Registration
- Now just modify the code as below to make the user register to the app.
// // ViewController.swift // UserRegistrationExample // // Created by Belal Khan on 05/02/17. // Copyright © 2017 Belal Khan. All rights reserved. // import Alamofire import UIKit class ViewController: UIViewController { //Defined a constant that holds the URL for our web service let URL_USER_REGISTER = "http://192.168.1.105/SimplifiediOS/v1/register.php" //View variables @IBOutlet weak var textFieldUsername: UITextField! @IBOutlet weak var textFieldPassword: UITextField! @IBOutlet weak var textFieldEmail: UITextField! @IBOutlet weak var textFieldName: UITextField! @IBOutlet weak var textFieldPhone: UITextField! @IBOutlet weak var labelMessage: UILabel! //Button action @IBAction func buttonRegister(_ sender: UIButton) { //creating parameters for the post request let parameters: Parameters=[ "username":textFieldUsername.text!, "password":textFieldPassword.text!, "name":textFieldName.text!, "email":textFieldEmail.text!, "phone":textFieldPhone.text! ] //Sending http post request Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON { response in //printing response print(response) //getting the json value from the server if let result = response.result.value { //converting it as NSDictionary let jsonData = result as! NSDictionary //displaying the message in label self.labelMessage.text = jsonData.value(forKey: "message") as! String? } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
Testing the Application
- Now just launch the application in Simulator.
- We have the success message. Now lets check the MySQL Database.
- Bingo! Its working absolutely fine.
Download Source Code
- If you are still having troubles you can get the source code from below link.
[sociallocker] iOS Registration Form Example Source Code [/sociallocker]
So thats all for this iOS Registration Form Example friends. Stay tuned and in the next post we will work on the same project to make the User Login option. And you can leave your comments for queries and feedbacks. Thank You 🙂
Mohamad Habibi says
Alhamdulillah, Belal Khan, finally there’s an iOS version of your simplifiedcoding.net, just can’t believe it!
Great job ! And I really mean it, because I find it very difficult to find online resources for learning iOS in easy way, until you come to the rescue 🙂
I wish you good luck, no matter what, and keep posting useful and easy resources.
Eric Park says
Thanks to Belal Kahn I am learning Xcode easily. However, after follow your instruction, my Xcode Console returns this response.
“FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)”
Can someone help me please?
Mr. Gemu says
abt alamofire it depends on the xcode version
Alanoud says
Thank you, can you please do the ios login example.
mukta ghosh says
my app build successfully but can’t run.it great threat.
application UIApplication 0x00007ff42ac00a50
self myiosapp.AppDelegate 0x000060800002e140
khadija haasn says
I have done the part related to the PHP Storm , but it did not work for me . It does not insert a new record to the database and it always shows not valid request message. What does cause this problem ?
sduoanmni ksdhkah says
http not accepted only https is accepted pls help. it is a nsapplicationtraportation error
korpo says
could you please do the login guide as well 🙂
Hizkia Nowaly says
i hv done all the part. i hv tryed using postman too and it works when i add data to mysql. but when i testing to application it didnt works anymore, the data cant be added to mysql. what does cause this problem?
Mr. Gemu says
I think u jus copast the script, try to drag fieldname and button rename with manually, nothing copast.
Mr. Gemu says
Thanks in advance, I need much more time to make it’s work, but finally I can. I am so happy, I hope god bless u
Hardik Dabhi says
Does This api work for afnetworking?
I am using objective c ,so for Api I have used AFnetworking ,but problem is that the registration is done completely but the response is in form of error.
Nan says
thank you Belal for great lesson , i rellay i meant it , i have problem when i’m useing [almofire] the Xcode can’t dealing with this class .
Nan says
i’m using Xcode 8
what i should replace it by?
Rasha says
thank u for great Lesson i’m follwing the insteraction then my Xcode Show this for me :
//converting it as NSDictionary
let jsonData = result as! NSDictionary
display ::
Cast from ‘String’ to unrelated type ‘NSDictionary’ always fails
what i shoud do ?
another question if i want to display Alert message not label Like u
where can i put this code ?
Satyajeet says
Hi Belal
I am trying to execute the code but i am getting an error “{“error”:true,”message”:”Some error occurred”}” . It seems my insert statement is failing, what i could be doing wrong ? When i tried to hard code values into the INSERT statement of DbOperations.php it worked
Mason says
Hey! thank you for such a great tutorial but I’m getting an error whenever I actually go to register (responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength))
I’ve tried looking this up but couldn’t find a solution.
alexus says
can you show the file structure for the actual hosting deployment?
Gino says
I don’t undestand how fix error:
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
I use xCode 8 and Swift 3
Can you help me, please?
fahad says
Hi
how I need cods to do application mobile
Daniel says
Hello, on my DbOperation.php file it says this error everytime I try to run a POST request:
– Parse error: syntax error, unexpected ‘->’ (T_OBJECT_OPERATOR) in /var/www/html/ComputAS/includes/DbOperation.php on line 20 .
However, the unexpected -> is used in your code and you code apparently works. Any fix for this ??
Kathi says
Gift for yourself buy cheap jerseys online,price favorite and
easy exchange or refund,come store: nba replica jersey