ios 如何快速连接mysql?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31468868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:54:23  来源:igfitidea点击:

How to connect mysql with swift?

iosmysqlswift

提问by David

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 find a solution work for me. Had any of you guys done this before?

我有一个网络应用程序,我想制作一个 iOS 应用程序,我不想使用 HTTP 请求,我的网站有自己的数据库(这是一个 MySQL 数据库)。我用谷歌搜索了很多,但找不到适合我的解决方案。你们有没有人以前做过这个?

回答by Belal Khan

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.

将 swift 连接到 mysql 和 php 非常容易。首先,您需要一个 REST API。您可以使用任何可用的框架来创建 rest api。您也可以仅使用 PHP 来编码您的 Web 服务。所以这里我将展示任何php框架的使用。

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 database connection.

然后创建另一个 php 文件来创建数据库连接。

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

}

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

最后,您需要创建将处理您的 http 请求的 php 文件。

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

现在只需在您的 iOS 应用程序上创建视图,然后在 buttonclick 上向您的 php 文件发送请求。代码如下。

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

您需要做的另一件事是在您的 Info.plist 文件中添加以下几行,这是因为默认情况下您无法向不安全的 url 发送请求,因此因为我们有 http,我们必须做最后一件事。

<!-- 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: iOS MySQL Database Tutorial

来源:iOS MySQL 数据库教程

回答by Ben Fried

Mobile apps generally connect to an API, not directly to a database. I know you said you didn't want to use HTTP request, but that's really the proper way to do it. Make a REST service using whatever programming language you like and do it right.

移动应用程序通常连接到 API,而不是直接连接到数据库。我知道你说过你不想使用 HTTP 请求,但这确实是正确的做法。使用您喜欢的任何编程语言制作 REST 服务并正确执行。

If you like JS, try out SailsJS on Node. It takes 5 minutes to make an API from a MySQL database. http://sailsjs.org

如果您喜欢 JS,请在 Node 上试用 SailsJS。从 MySQL 数据库制作 API 需要 5 分钟。 http://sailsjs.org

回答by Oleg

I met the same issue some time ago. I developed the library OHMySQL. Take a look, it works on iOS and macOS. You write your app in Swift or Objective-C.

前段时间我遇到了同样的问题。我开发了库OHMySQL。看一看,它适用于 iOS 和 macOS。你用 Swift 或 Objective-C 编写你的应用程序。

enter image description here

在此处输入图片说明

回答by user1700737

You should implement a REST interface for your database (i.e. in node as suggested above). Or you could move you database to AZURE and use the Microsoft "out of the box" API for iOS. This will give you security also (if you need that) You could also implement a web service in the backend and use that from iOS.

您应该为您的数据库实现一个 REST 接口(即在上面建议的节点中)。或者,您可以将数据库移动到 AZURE 并使用适用于 iOS 的 Microsoft“开箱即用”API。这也将为您提供安全性(如果您需要)您还可以在后端实现一个 Web 服务并从 iOS 使用它。