[英]How to connect mysql with swift?
我有一个网络应用程序,我想制作一个iOS应用程序,我不想使用HTTP请求,我的网站有自己的数据库(这是一个MySQL数据库)。 我google了很多,但我找不到适合我的解决方案。 你们之前有人这样做过吗?
将swift连接到mysql和php非常容易。 首先,您需要一个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['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);
现在只需在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.
}
}
你需要做的另一件事是在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数据库教程
移动应用通常连接到API,而不是直接连接到数据库。 我知道你说你不想使用HTTP请求,但这确实是正确的方法。 使用您喜欢的任何编程语言制作REST服务并正确执行。
如果您喜欢JS,请在Node上试用SailsJS。 从MySQL数据库制作API需要5分钟。 http://sailsjs.org
我前段时间遇到过同样的问题。 我开发了库OHMySQL 。 看一下,它适用于iOS和macOS。 您在Swift或Objective-C中编写应用程序。
您应该为数据库实现REST接口(即,如上所述在节点中)。 或者您可以将数据库移动到AZURE并使用Microsoft的“开箱即用”API for iOS。 这也将为您提供安全性(如果您需要)您还可以在后端实现Web服务并使用iOS中的Web服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.