Search code examples
phpjsonpostswift3alamofire

retrieve json data through $_POST from post request of alamofire swift3?


guys, i am having problem of posting json data through alamofire 4 with swift3 and also the problem of retrieving the json data at XAMPP server side using php. My swift 3 code did trigger the php script at XAMPP, but somehow i can't get it through $_POST variable in php Here is my code,

func uploadImage(image: UIImage){
    //Now use image to create into NSData format
    let imageData:NSData = UIImagePNGRepresentation(image)! as NSData      
    //convert the nsdata to base64 encoded string
       let strBase64:String = imageData.base64EncodedString(options: .lineLength64Characters)
   // let parameters = ["image": strBase64] as Dictionary
    let parameters = ["image": strBase64]      
    print(strBase64) 
  Alamofire.request("http://localhost/Test/api/UploadPhoto.php",method: .post, parameters: parameters, encoding: JSONEncoding.default).response { response in            
    print(response)                   
                }   
}

Here is my server side code(the script did get triggered by the call from alamofire, but somehow i just can't get the data through calling$_POST["image"])

    <?php
//scripts below did get triggered, but can't get the json data through          calling $_POST["image"];
$imageString = $_POST["image"];
$filename_path = md5(time().uniqid()).".png"; 
$data = base64_decode($imageString);
file_put_contents('../AllImages/'.$filename_path, $data);
echo json_encode($_POST["image"]);
?>   

if possible, please help me, i have been struggled for nearly a week, but can't find many clues Thank you


Solution

  • i have found a way to solve this problem, basically, i used urlsession.shared.datatask to help me instead of alamofire with the post request, here is my ios side code

         func uploadImage(image: UIImage, completionHandler: @escaping (String) ->()){
    
       // Now use image to create into NSData format
                let imageData:NSData = UIImagePNGRepresentation(image)! as NSData
    
                //convert the nsdata to base64 encoded string
    
                   let strBase64:String = imageData.base64EncodedString(options: .lineLength64Characters)
        // prepare json data
        let json: [String: Any] = ["image": strBase64]
    
        let jsonData = try? JSONSerialization.data(withJSONObject: json)
    
        // create post request
        let url = URL(string: "http://10.10.10.72/Test/api/UploadPhoto.php")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
    
        // insert json data to the request
        request.httpBody = jsonData
    
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
    
            do {
                guard let data = data else {
                    throw JSONError.NoData
                }
                guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else {
                    throw JSONError.ConversionFailed
                }
    
                 completionHandler(json["sign"] as! String)
    
            } catch let error as JSONError {
                print(error.rawValue)
            } catch let error as NSError {
                print(error.debugDescription)
            }
    
            }
        task.resume()
    }
    

    i used dictionary to store my data, and converted it to json data format to be sent to server

         let json: [String: Any] = ["image": strBase64]
         let jsonData = try? JSONSerialization.data(withJSONObject: json)
    

    Then at the php side, i retrieved it by using

        $entityBody = file_get_contents('php://input');
    

    , then i decoded from json which produced me an array and i can access my value by referencing image, so full php side of code as below:

        <?php
    //get the posted json data
     $entityBody = file_get_contents('php://input');
    //decode the json data
    $decoded = json_decode($entityBody, TRUE);
    $imageString = $decoded["image"];
    //create a unique name for the image
     $filename_path = md5(time().uniqid()).".png"; 
    //converted the image string back to image
     $data = base64_decode($imageString);
    //put it on the desired location
    file_put_contents('../AllImages/uploads/signature/'.$filename_path, $data);
     $response = array();
     //create the response 
     $response['sign'] = '../AllImages/uploads/signature/'.$filename_path;
     echo json_encode($response);
     ?>
    

    do note here, i encode the json data again to be sent back as a response from php to my ios side, and you need to decode the response from json, so the full idea is if you encode the value to json from one side, you need to decode it from another side to access the value properly, correct me if i am wrong, i am glad that my app is up and running now with all the requests now :D