2021年1月7日 星期四

Ubuntu 20.04+PHP -資料存取(四) POST+JSON+swift

參考來源:

Creating task for POST request to PHP script to add entries in MySQL database

 https://stackoverflow.com/questions/55990599/creating-task-for-post-request-to-php-script-to-add-entries-in-mysql-database

Receive JSON POST with PHP

 https://stackoverflow.com/questions/18866571/receive-json-post-with-php


 建立檔案名稱: t4.php 

並儲存到  https://www.mydomain.com/htdocs/t4.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"];

    

   $response['error']=false;

   $response['message']='item1 successfully';

  }

  echo json_encode($response);

?>


建立檔案名稱: t4.swift

iOS XCode 12.3 


import Foundation

import UIKit

func PhpJsonTest()

{

 // created NSURL

  let urlString = URL(string: "https://www.mydomain.com/htdocs/t4.php")!

  var request = URLRequest(url: urlString)


 // setting the method to post

  request.httpMethod = "POST"

        

 // creating the post parameter by concatenating the keys and values from text field

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

                            "item2": "DEF",

                            "item3": "HIJ",

                            "item4": "567"]

 let jsonData = try? JSONSerialization.data(withJSONObject: json)

 // insert json data to the request

 request.httpBody = jsonData


 // creating a task to send the post request

 let task = URLSession.shared.dataTask(with: request)

 {

  data, response, error in

   guard let data = data, error == nil else {

    DPrint(error?.localizedDescription ?? "No data")

     return

   }

  // parsing the response

  do

  {

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

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

   {

    DPrint(responseJSON)

    var msg : String!

    // getting the json response

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

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

   }

  }

  catch

  {

   DPrint(error)

  }

 }

 //executing the task

 task.resume()

}

沒有留言:

張貼留言