How to connect mysql with swift?
Connecting swift to mysql and php is very easy. First you need a REST API. You can create a rest api using any framework available. You can also code your web service with PHP only. So, here I will show you how to use any PHP framework.
So, first create a file to store your database constants.
<?php
/**
* Created by PhpStorm.
* User: Belal
* Date: 12/08/16
* Time: 7:58 PM
*/
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'iphone');
Then create another php file to create a database connection.
<?php
class DbConnect
{
private $conn;
function __construct()
{
}
/**
* Establishing database connection
* @return database connection handler
*/
function connect()
{
require_once 'Config.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;
}
}
Now you need one more file to handle database operations.
<?php
class DbOperation
{
private $conn;
//Constructor
function __construct()
{
require_once dirname(__FILE__) . '/Config.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 createTeam($name, $memberCount)
{
$stmt = $this->conn->prepare("INSERT INTO team(name, member) values(?, ?)");
$stmt->bind_param("si", $name, $memberCount);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
}
Finally, you need to create a php file that will handle your HTTP request.
<?php
//creating response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($teamName,$memberCount)){
$response['error']=false;
$response['message']='Team added successfully';
}else{
$response['error']=true;
$response['message']='Could not add team';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
Now just create views in your iOS app and on the buttonclick, send a request to your php file. The code looks like this.
//
// ViewController.swift
// SwiftPHPMySQL
//
// Created by Belal Khan on 12/08/16.
// Copyright Β© 2016 Belal Khan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//URL to our web service
let URL_SAVE_TEAM = "http://192.168.1.103/MyWebService/api/createteam.php"
//TextFields declarations
@IBOutlet weak var textFieldName: UITextField!
@IBOutlet weak var textFieldMember: UITextField!
//Button action method
@IBAction func buttonSave(sender: UIButton) {
//created NSURL
let requestURL = NSURL(string: URL_SAVE_TEAM)
//creating NSMutableURLRequest
let request = NSMutableURLRequest(URL: requestURL!)
//setting the method to post
request.HTTPMethod = "POST"
//getting values from text fields
let teamName=textFieldName.text
let memberCount = textFieldMember.text
//creating the post parameter by concatenating the keys and values from text field
let postParameters = "name="+teamName!+"&member="+memberCount!;
//adding the parameters to request body
request.HTTPBody = postParameters.dataUsingEncoding(NSUTF8StringEncoding)
//creating a task to send the post request
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil{
print("error is \(error)")
return;
}
//parsing the response
do {
//converting resonse to NSDictionary
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
//parsing the json
if let parseJSON = myJSON {
//creating a string
var msg : String!
//getting the json response
msg = parseJSON["message"] as! String?
//printing the response
print(msg)
}
} catch {
print(error)
}
}
//executing the task
task.resume()
}
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.
}
}
Another thing you need to do is add the following lines inside your Info.plist file, because by default you cannot send a request to non-secure urls, since we have http, we have to do that last.
<!-- add from here -->
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
</dict>
<!-- end of the code -->
Source: MySQL for MySQL Tutorial
source to share
Mobile apps usually connect to an API rather than directly to a database. I know you said you didn't want to use an HTTP request, but this is really the correct way to do it. Make a REST service using whatever programming language you like and do it right.
If you like JS, try SailsJS on Node. It takes 5 minutes to create API from MySQL database. http://sailsjs.org
source to share
You should implement the REST interface for your database (i.e. in node as suggested above). Or you can move your database to AZURE and use Microsoft's out-of-the-box API for iOS. It will also give you security (if you need it). You can also implement a web service in the backend and use it in iOS.
source to share