2021年1月11日 星期一

Ubuntu 20.04+PHP -資料存取(七) iOS swift Alamofire 5.2 POST

  本程式範例只適用於 Alamofire 5.2 

------------------------------------ 

參考來源:

 利用 Postman 來測試 Web Service 的工具

  https://franksios.medium.com/postman-測試web-service的工具-c7726997868a#.45rlrqve9

 Formatting JSON Data for Postman 

  https://stackoverflow.com/questions/38574039/formatting-json-data-for-postman

 Alamofire 

  https://github.com/Alamofire/Alamofire

 SwiftyJSON 

  https://github.com/SwiftyJSON/SwiftyJSON

 利用 Alamofire 處理 Http 請求 

  https://medium.com/allen的技術筆記/利用-alamofire-處理-http-請求-eb62f37118ca

 Alamofire學習(三)Request上篇 

  https://www.mdeditor.tw/pl/gaNU/zh-tw

------------------------------------ 

 Installation Alamofire

  CocoaPods

   pod 'Alamofire', '~> 5.2'

------------------------------------ 

建立檔案名稱: t7.php (內容同 t5,php)

並儲存到  https://www.mydomain.com/htdocs/t7.php


<?php

   $response = array();

   

   $data = json_decode(file_get_contents('php://input'), true);

   $item1 = $data["item1"];

   $item2 = $data["item2"];

   $item3 = $data["item3"];

   $item4 = $data["item4"];


   require_once ("config.php");

   $conn = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

   if( !$conn) 

   {

    die("Connection failed: " . mysqli_connect_error());

   }

   else

   {

    $sql = "INSERT INTO mytabelname (name1, name2, name3, member) value ('$item1','$item2','$item3','$item4')";

    if (mysqli_query($conn, $sql)) 

    {

     $response['error']=false;

     $response['message']='mytabelname added successfully';

    }

    else 

    {

     echo "Error: " . $sql . "<br>" . mysqli_error($conn);

    }

    mysqli_close($conn);            

  }

  echo json_encode($response);

?>

------------------------------------

開啟 Postman 測試

. 選擇 POST

  輸入網址 https://www.mydomain.com/htdocs/t7.php

  Body 選擇 raw 和 JSON

  傳送資料填入下列

{

  "item1": "ABC",

  "item2": "DEF",

  "item3": "XYO",

  "item4": "356"

}

. 點選 Send



. 結果

  $postdata = file_get_contents("php://input", 'r');

  $jsondata = json_decode($postdata, true);

  $item1 = $jsondata["item1"];    

  使用上面三行 就可以取得傳入之資料 

   

------------------------------------

建立檔案名稱: t7.swift

iOS XCode 12.3 

import Foundation

import UIKit

func PhpJsonTest()

{

 let params: [String: Any] = ["item1": "ABC",

                              "item2": "DEF",

                              "item3": "HIJ",

                              "item4": "889"]

  AF.request( "https://www.mydomain.com/htdocs/t7.php", method: .post,  parameters: params, encoding: JSONEncoding.default)

   .validate()

   .responseData(emptyResponseCodes: [200, 204, 205]) { response in

   

    DPrint( response)

    switch response.result

    {

     case .success( let value):

       DPrint("Payment successful")

       if let responsedata = response.data, let str = String(data: responsedata, encoding: String.Encoding.utf8)

       {

        DPrint("FUNC: \(#file), \(#function), \(String(describing: str))")

       }

       let responseJSON = (try? JSONSerialization.jsonObject(with: value, options: []))

       if let responseJSON = responseJSON as? [String: Any]

       {

        DPrint(responseJSON)

        var msg : String!

        msg = responseJSON["message"] as! String?

        DPrint("FUNC: \(#file), \(#function), \(String(describing: msg))")

       }

       

     case .failure(let error):

       if (response.data?.count)! > 0

       {

        DPrint(error)

       }

       DPrint("Error Code: \(error._code)")

       DPrint("Error Messsage: \(error.localizedDescription)")

       if let data = response.data, let str = String(data: data, encoding: String.Encoding.utf8)

       {

        DPrint("Server Error: " + str)

       }

       DPrint("error processing the payment-> ", error.localizedDescription)

    }

   }

}

------------------------------------
建立檔案名稱: t71.swift
iOS XCode 12.3 使用 NSDictionary 

func PhpJsonTest()
{
 let params: [String: Any] = ["item1": "ABC",
                              "item2": "DEF",
                              "item3": "HIJ",
                              "item4": "889"]
  AF.request( "https://www.mydomain.com/htdocs/t7.php", method: .post,  parameters: params, encoding: JSONEncoding.default)
   .validate()
   .responseData(emptyResponseCodes: [200, 204, 205]) { response in
   
    DPrint( response)
    switch response.result
    {
     case .success( let value):
       DPrint("Payment successful")
       if let responsedata = response.data, let str = String(data: responsedata, encoding: String.Encoding.utf8)
       {
        DPrint("FUNC: \(#file), \(#function), \(String(describing: str))")
       }
       
       if let responseJson = (try? JSONSerialization.jsonObject(with: value, options: []))
       {
        let nsdresponse = responseJson as! NSDictionary
        let msg = nsdresponse.object(forKey: "message")!
        DPrint("FUNC: \(#file), \(#function), \(String(describing: msg))")
       }
       
     case .failure(let error):
       if (response.data?.count)! > 0
       {
        DPrint(error)
       }
       DPrint("Error Code: \(error._code)")
       DPrint("Error Messsage: \(error.localizedDescription)")
       if let data = response.data, let str = String(data: data, encoding: String.Encoding.utf8)
       {
        DPrint("Server Error: " + str)
       }
       DPrint("error processing the payment-> ", error.localizedDescription)
    }
   }
}

沒有留言:

張貼留言