Я новичок в Swift и пытаюсь сделать простое приложение для размещения имен в базе данных MySQL. Когда я запускаю скрипт Swift в симуляторе, в базе данных ничего не меняется. Что я делаю неправильно?
Спасибо заранее!
connect.php
//Connect to Database
$user="something_net_something";
$host="something.net.mysql";
$password="SecretPassword";
$database="something_net_something";
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
mysqli_select_db($connection,$database) or die ("couldn’t select database");
Function.php
header('Content-Type: text/html; charset=ISO-8859-1');
//Connect to Database
include "Connect.php";
//getting values
$fname = $_POST['Fname'];
$lname = $_POST['Lname'];
//query
$QRY="INSERT INTO oneiros_aether_personage (Fname, Lname) VALUES ($fname, $lname)";
if (mysqli_query($connection, $QRY)) {
$response['error']=false;
$response['message']="New record created successfully";
} else {
$response['error']=true;
$response['message']="Error: " . $QRY . "<br>" . mysqli_error($connection);
}
echo json_encode($response);
mysqli_close($connection);
ViewController.swift
import UIKit
class ViewController: UIViewController {
//URL to our web service
let URL_ADD_PERSONAGE = "http://www.something.net/Function.php"
//TextFields declarations
@IBOutlet weak var textFieldFname: UITextField!
@IBOutlet weak var textFieldLname: UITextField!//Button action method
@IBAction func buttonSave(sender: UIButton) {
//created NSURL
let requestURL = URL(string: URL_ADD_PERSONAGE)
//creating NSMutableURLRequest
let request = NSMutableURLRequest(url: requestURL! as URL)
//setting the method to post
request.httpMethod = "POST";
//getting values from text fields
let fname = textFieldFname.text
let lname = textFieldLname.text
//creating the post parameter by concatenating the keys and values from text field
let postParameters = "Fname="+fname!+"&Lname="+lname!;
//adding the parameters to request body
request.httpBody = postParameters.data(using: String.Encoding.utf8)//creating a task to send the post request
let task = URLSession.shared.dataTask(with:request as URLRequest){
data, response, error in
if error != nil{
print("error is \(error)")
return;
}
//parsing the response
do {
//converting resonse to NSDictionary
let myJSON = try JSONSerialization.jsonObject(with: 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 я добавил
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
твой код отлично работает со мной,
проверить URL_ADD_PERSONAGE
переменная, IBOutlet
и другие.
Логика подключения не имеет ошибок.
Других решений пока нет …