How to connect mysql with swift?

前端 未结 4 2026
悲哀的现实
悲哀的现实 2020-12-13 05:22

I had a web app and I want to make a iOS app, I don\'t want to use HTTP request, my website has its own database (which is a MySQL database). I googled a lot, but I can\'t f

4条回答
  •  孤城傲影
    2020-12-13 05:59

    Connecting swift to mysql and php is very easy. First you need a REST API. You can create a rest api by using any framework available. You can also code your Web Service using PHP only. So here I will show the use of any php framework.

    So first create a file to store your database constants.

    Then create another php file to create database connection.

    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 your database operations.

    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;
            }
        }
    
    }
    

    Lastly you need to create the php file that will handle your http request.

    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 on your iOS Application and on buttonclick send a request to your php file. The code is as follows.

    //
    //  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.
        }
    
    
    }
    

    One more thing you need to do is add the following lines inside your Info.plist file, this is because by default you cannot send request to not secured urls so because we have http we have to do this last thing.

    
        NSAppTransportSecurity
        
            NSAllowsArbitraryLoads
            
            NSExceptionDomains
            
                yourdomain.com
                
                    NSIncludesSubdomains
                    
                    NSThirdPartyExceptionRequiresForwardSecrecy
                    
                
            
        
        
    

    Source: iOS MySQL Database Tutorial

提交回复
热议问题