Riki Dev Riki Dev - 19 days ago 8
Swift Question

Read return value php on IOS application

Hello I'm writing an ios swift 3 application to communicate with a website, the app after doing a number of things should return a type value of false or true, but it does not happen you can tell me where I'm wrong and how to correct the mistake!

VALUE RETURN at swift:
....response = Optional( { URL: "http://....myurl.php"}.....

SWIFT CODE:

let myUrl = URL(string: "http://....myurl.php");

var request = URLRequest(url:myUrl!)

request.httpMethod = "POST"// Compose a query string

let postString = "username=James&password=Bond";

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

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

if error != nil
{
print("error=\(error)");
// return false
}

print("response = \(response)")

}
task.resume()

return 0;


PHP CODE:

include 'user.php';

$user = new User();
$username= $_REQUEST["username"];
$password = $_REQUEST["password"];

if($user->login($username,$password)==true){
echo json_encode("true");
}

else{
echo json_encode("false");
}


ERROR IMAGE:

ERROR PICTURE

Answer

You need to look into data and not response. And maybe you should encapsulate your return value in your PHP code, like this for example:

if($user->login($username,$password)==true){
    echo '{"success":true}';
 }else{
     echo '{"success":false}';
 }

And then get the result in swift:

func login(request_completed:@escaping (_ succeded:Bool) -> ()) {
    let myUrl=URL(string: "http://....myurl.php");
    var request=URLRequest(url:myUrl!)
    request.httpMethod="POST"
    let postString = "username=James&password=Bond";
    request.httpBody = postString.data(using: String.Encoding.utf8);

    let task=URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
        guard data != nil else {
            print("no data found")
            request_completed(false)
            return
        }

        do{
            if let jsonData=try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary{
                print(jsonData)
                let success=jsonData.value(forKey: "success") as! Bool
                if success{
                    print("login succeded")
                    request_completed(true)
                    return
                 }else{
                    print("login failed")
                    request_completed(false)
                    return
                }
            }else{
                print("could not parse json")
                request_completed(false)
            }
        }catch{
            print("request failed")
            request_completed(false)
        }
    })
    task.resume()
}