SwiftでMySQLに接続する場合のデータ取得方法について教えてください。
iPadで名前と年齢を入力して保存ボタンをタップするとMySQLにデータを保存させる処理を作成しています。
Swift、MySQL1、JSONとの連携部分に問題があると思うのですが、どのようにデバッグを進めれればよいのか、ご教示いただければ幸いです。
下記ホームページを参考にしています。
リンク内容
エラー内容:
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
環境:
MacPC macOS Ver10.14.5
Swift4.2
MAMP Ver5.3
PHP Ver7.3.1
MySQL Ver5.7.25
ディレクトリ:
MAMP/htdocs/WebService
MySQL:
データベース db_boy
テーブル m_boy (name, old)
PHP:
config.php <?php define('DB_HOST','localhost'); define('DB_NAME','db_boy'); define('DB_USERNAME','boy'); define('DB_PASSWORD','boy1234'); define('DB_CHARSET','utf8'); ?> DBConnect.php <?php class DbConnect { private $conn; function __construct(){ } /* *データベースへの接続 */ function connect(){ require_once 'config.php'; //Mysql DataBaseに接続 $this -> conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); //DB接続時のエラーがないか確認 if(mysqli_connect_errno()){ echo "データベースに接続されませんでした" . mysqli_connect_errno(); } //接続リソースの保持 return $this -> conn; ?> DbOparation.php <?php /* *DBに対する指示ファイル */ class DbOparation { private $conn; //コンストラクター function __construct(){ require_once dirname(__FILE__).'/config.php'; require_once dirname(__FILE__).'/DbConnect.php'; //DBに接続 $db = new DbConnect(); $this -> conn = $db->connect(); } //新しいユーザーを作成する機能 public function saveBoy($name, $Old) { $stmt = $this->conn->prepare("INSERT INTO boy(name, old) values(?, ?)"); $stmt -> bind_param("ss", $name, $Old); $result = $stmt -> execute(); $stmt -> close(); if($result) { return true; }else{ return false; } } ?> saveBoy.php <?php /* *実際にDBに値を挿入する処理をする */ // 返信が配列になるようにする $response = array(); if($_SERVER['REQUEST_METHOD']=='POST'){ //値の取得 $boyName = $_POST['name']; $boyOld = $_POST['old']; //DBファイルの操作 require_once '../includes/DbOperation.php'; $db = new DbOparation(); //値の挿入 if($db->saveBoy($name,$Old)){ $response['error']=false; $response['message']= '登録が完了しました'; }else{ $response['error'] = true; $response['message'] = '登録できませんでした'; } }else{ $response['error'] = true; $response['messgae'] = 'あなたは承認されていません'; } echo json_encode($responce); ?>
Swift:
import UIKit class ViewController: UIViewController { // URL to our web service let URL_SAVE_BOY = "http://localhost/WebService/api/saveBoy.php" @IBOutlet weak var NameFeild: UITextField! @IBOutlet weak var oldFeild: UITextField! @IBAction func saveBtn(_ sender: UIButton) { // created NSURL let requestURL = NSURL(string: URL_SAVE_BOY) // creating NSMutableURLRequest let request = NSMutableURLRequest(url: requestURL! as URL) // setting the method tp post request.httpMethod = "POST" // テキストフィールドから値を取得 let boyName = NameFeild.text let boyOld = oldFeild.text // でキスとフィールドからキーと値を連結してpostパラメータを生成 let postParameters = "name="+boyName!+"&old="+boyOld!; // ボディをリクエストするためのパラメータを追加 request.httpBody = postParameters.data(using: String.Encoding.utf8) // 投稿要求を送信するタスクを作成 let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in if error != nil { //print("error is (error)") print("(error ?? "nil" as! Error)") return; } // 返ってきたJsonの解析 do { // NSDictionaryに変換 let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary // jsonデータの解析 if let parseJSON = myJSON{ // stringの生成 var msg : String! //jsonからのレスポンスを取得 msg = parseJSON["message"] as! String? // 返ってきたものを表示 print(msg ?? "text is nil") } }catch{ print(error) } } task.resume() } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。