我有一个网络应用程序,我想制作一个 iOS 应用程序,我不想使用 HTTP 请求,我的网站有自己的数据库(这是一个 MySQL 数据库)。我在谷歌上搜索了很多,但找不到适合我的解决方案。你们以前有人做过吗?
最佳答案
将 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 应用程序上创建 View ,然后在单击按钮时向您的 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 - 如何用swift连接mysql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31468868/