iOS   发布时间:2022-05-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 如何使用swift连接mysql?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

我有一个网络应用程序,我想制作一个iOS应用程序,我不想使用http请求,我的网站有自己的数据库(这是一个MySQL数据库).我google了很多,但我找不到适合我的解决方案.你们之前有没有人这样做过? 将swift连接到mysql和php非常容易.首先,您需要一个REST API.您可以使用任何可用的框架创建rest api.您也可以仅使用php对Web服务进行编码.所以在这里我将展示任何php
我有一个网络应用程序,我想制作一个iOS应用程序,我不想使用http请求,我的网站有自己的数据库(这是一个MysqL数据库).我google了很多,但我找不到适合我的解决方案.你们之前有没有人这样做过?

解决方法

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

首先创建一个文件来存储数据库常量.

<?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');

然后创建另一个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;
    }
}

现在,您还需要一个文件来处理数据库操作.

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

}

最后,您需要创建将处理您的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['@R_262_8798@ge']='Team added successfully';
    }else{

        $response['error']=true;
        $response['@R_262_8798@ge']='Could not add team';
    }

}else{
    $response['error']=true;
    $response['@R_262_8798@ge']='You are not authorized';
}
echo json_encode($responsE);

现在只需在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.httpR_519_11845@ethod = "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["@R_262_8798@ge"] 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.
    }


}

你需要做的另一件事是在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 -->

资料来源:iOS MySQL Database Tutorial

@H_673_64@

大佬总结

以上是大佬教程为你收集整理的ios – 如何使用swift连接mysql?全部内容,希望文章能够帮你解决ios – 如何使用swift连接mysql?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。