简体   繁体   中英

How do I get this snippet of Swift code to receive the returned values from PHP script?

I am running a short Swift script to post some variables a PHP script and then read the returned value:

  let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/createCommunity.php");

    var request = URLRequest(url:myUrl!);
    request.httpMethod = "POST";

    let postString = "communityname=\(communityName!)&code=\(communityCode)&email=\(myEmail!)";

    request.httpBody = postString.data(using: String.Encoding.utf8);

    let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]

           print (json["code"]);
           print (json["email"]);
           print (json["communityname"]);


        }
        task.resume()
    }

In my PHP code below I simply want to receive the values, and then return them in an array:

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


require("Conn.php");
require("MySQLDao.php");

$email = htmlentities($_POST["email"]);
$code = htmlentities($_POST["code"]);
$communityname = htmlentities($_POST["communityname"]);

$returnValue = array();

$returnValue["code"] = $code;
$returnValue["email"] = $email;
$returnValue["communityname"] = $communityname;

echo json_encode($returnValue);

?>

I know I am doing something wrong at the end of the Swift code but I don't know what.

I am getting this error for the let task line:

Invalid conversion from throwing function of type '(Data?, URLResponse?, Error?) throws -> ()' to non-throwing function type '(Data?, URLResponse?, Error?) -> Void'

Maybe you did not include all your code, but... are you calling task.resume() ?

Try this:

let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/createCommunity.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";

let postString = "communityname=\(communityName!)&code=\(communityCode)&email=\(myEmail!)";
request.httpBody = postString.data(using: String.Encoding.utf8);

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let json = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject] {
        print (json["code"]);
        print (json["email"]);
        print (json["communityname"]);
    }
}

task.resume()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM