[Swift inXcode]Connect my swift app to mySQL

2016-01-23

In the previous post, I have written an article about Parse signUp and signIn. However, Parse will stop service in Jan 27th, 2017. Instead of using parse, I will introduce how to use mysql to create signUp and signIn, to some extent, how to connect the swift app to mySQL.

There are some basic knowledge for the connection, make sure you have worked with php before 🙂 The basic four steps are below:

  1. You have a server which has already installed apache, php and mysql(LAMP is also allowed)
  2. We write some php code to execute the mysql query
  3. Using our app to request that url and to run step 2
  4. Receive the data back from that URL

You have a server which has already installed apache, php and mysql

I usually use amazon AWS as my server, to install apache, php, mysql, you can find some tutorial on the internet. If you have any question feel free to comment below, I will write one as well. Official aws document Try this link, if you are not sure now.

We write some php code to execute the mysql query

The basic idea is to execute these mysql query. For here, I will use two basic files, one called Conn.php, it will include some mysql connection settings:

1
2
3
4
5
6
7
8
9
10
<?php
class Conn {
public static $dbhost = "localhost";
public static $dbuser = "root";
public static $dbpass = "yourpassword";
public static $dbname = "mydb";
}
?>

Filling that string with your own settings. Then let’s have a quick look for another file, MySQLDao.php: I may include some simple function for signUp and signin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
class MySQLDao {
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $conn = null;
var $dbname = null;
var $result = null;
function __construct() {
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
public function openConnection() {
$this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if (mysqli_connect_errno())
echo new Exception("Could not establish connection with database");
}
public function getConnection() {
return $this->conn;
}
public function closeConnection() {
if ($this->conn != null)
$this->conn->close();
}
public function getUserDetails($email)
{
$returnValue = array();
$sql = "select * from users where email='" . $email . "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
public function getUserDetailsWithPassword($email, $userPassword)
{
$returnValue = array();
$sql = "select id,email,password from users where email='" . $email . "' and password='" .$userPassword . "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
public function registerUser($email, $password)
{
$sql = "insert into users set email=?, password=?";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->bind_param("ss", $email, $password);
$returnValue = $statement->execute();
return $returnValue;
}
}
?>

The if you need userLogin, the code should be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
require("Conn.php");
require("MySQLDao.php");
$email = htmlentities($_POST["email"]);
$password = htmlentities($_POST["password"]);
$returnValue = array();
if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$secure_password = md5($password);
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetailsWithPassword($email,$secure_password);
if(!empty($userDetails))
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is registered";
echo json_encode($returnValue);
} else {
$returnValue["status"] = "error";
$returnValue["message"] = "User is not found";
echo json_encode($returnValue);
}
$dao->closeConnection();
?>

Then, the code for register:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
require("Conn.php");
require("MySQLDao.php");
$email = htmlentities($_POST["email"]);
$password = htmlentities($_POST["password"]);
$returnValue = array();
if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetails($email);
if(!empty($userDetails))
{
$returnValue["status"] = "error";
$returnValue["message"] = "This email has been registered.:-(";
echo json_encode($returnValue);
return;
}
$secure_password = md5($password); // I do this, so that user password cannot be read even by me
$result = $dao->registerUser($email,$secure_password);
if($result)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "You have registered successfully.:-)";
echo json_encode($returnValue);
return;
}
$dao->closeConnection();
?>

Here you need to upload all these php code on your server and remember, when you connect our app to the mysql server is to use these php code.

Using our app to request that url and to run step 2

Receive the data back from that URL

Here is my swift code for query these data, this is the code for login:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
let myUrl = NSURL(string: "http://hanslen.me/php/userLogin.php")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = "email=\(userEmail)&password=\(userPassword)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if(error != nil){
print("error=\(error)")
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json
{
let resultValue = parseJSON["status"] as? String
print("results: \(resultValue)")
let resultMessage = parseJSON["message"] as? String
print("message: \(resultMessage)")
let returnValue = parseJSON["returnwow"] as? String
print("return0.0:\(returnValue)")
dispatch_async(dispatch_get_main_queue(), {
if(resultValue == "Success"){
self.createAlertMsg("Success", Message: "Log in success")
self.saveContext()
}
else{
self.createAlertMsg("Error", Message: "The Email and Password does not match")
}
})
}
}catch
{
print(error)
}

Then here is the code for register:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
let URL:NSURL = NSURL(string: "http://hanslen.me/php/userRegister.php")!
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "POST"
let email:String = emailTF.text!
let password:String = passwordTF.text!
let postString = "email=\(email)&password=\(password)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if(error != nil){
print("error = \(error)")
return
}
// var err:NSError?
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json
{
let resultValue = parseJSON["status"] as? String
print("results: \(resultValue)")
var isUserRegistered:Bool = false
if(resultValue == "Success"){
isUserRegistered = true
}
var messageToDisplay:String = parseJSON["message"] as! String!
if(!isUserRegistered){
messageToDisplay = parseJSON["message"] as! String!
}
print("message to display",messageToDisplay)
dispatch_async(dispatch_get_main_queue(), {
self.createAlertMsg("Success", Message: messageToDisplay)
})
}
}catch
{
print(error)
}
}
task.resume()


Comments: