2

I want a variable in php to get over in swift (or get the value for the variable). How can I do that?

$name = "William";

How can I get this string "William" to my Swift script? Can anyone help me?

I know it's something with JSON and POST or something but otherwise I am complete lost.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • The proposed duplicate question (http://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) does not answer this question. It only addresses the client-side half of the question. The more interesting issue raised by this question is what one needs to do in PHP in order to deliver `$name` to the client app. And that is not addressed in the other question at all. – Rob Jan 03 '15 at 14:19

2 Answers2

5

When you want to get data from PHP to an iOS device, I would recommend having the PHP code send it as JSON. JSON is easier for the the client app to parse (especially as your web service responses get more complicated) and it makes it easier to differentiate between a valid response and some generic server error).

To send JSON from PHP, I generally create an "associative array" (e.g., the $results variable below), and then call json_encode:

<?php

    $name = "William";

    $results = Array("name" => $name);

    header("Content-Type: application/json");
    echo json_encode($results);

?>

This (a) specifies a Content-Type header that specifies that the response is going to be application/json; and (b) then encodes $results.

The JSON delivered to the device will look like:

{"name":"William"}

Then you can write Swift code to call NSJSONSerialization to parse that response. For example, in Swift 3:

let url = URL(string: "http://example.com/test.php")!
let request = URLRequest(url: url)

// modify the request as necessary, if necessary

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data else {
        print("request failed \(error)")
        return
    }

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], let name = json["name"] {
            print("name = \(name)")   // if everything is good, you'll see "William"
        }
    } catch let parseError {
        print("parsing error: \(parseError)")
        let responseString = String(data: data, encoding: .utf8)
        print("raw response: \(responseString)")
    }
}
task.resume()

Or in Swift 2:

let url = NSURL(string: "http://example.com/test.php")!
let request = NSMutableURLRequest(URL: url)

// modify the request as necessary, if necessary

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
    guard let data = data else {
        print("request failed \(error)")
        return
    }

    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: String], let name = json["name"] {
            print("name = \(name)")   // if everything is good, you'll see "William"
        }
    } catch let parseError {
        print("parsing error: \(parseError)")
        let responseString = String(data: data, encoding: NSUTF8StringEncoding)
        print("raw response: \(responseString)")
    }
}
task.resume()
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Doesn't work anymore. You can't give an error in the parameters anymore. Because the function throws now. – Bas Aug 15 '16 at 17:16
  • @Bas - Yes, that was written in the Swift 1.x days. Back when we had `println`, no `OptionSet`, no throwing by `NSJSONSerialization‌`​, etc. I've updated for Swift 2 and 3. – Rob Aug 15 '16 at 17:38
  • Exactly! Thanks for updating. – Bas Aug 15 '16 at 17:51
3

I'm answering this as an iOS/PHP dev rather than a Swift programmer.

You need to send an HTTP request to the webserver hosting the PHP script, which will return the contents of the web page given any specified parameters.

For example, if you sent an GET HTTP request to the following PHP script, the response would be "William" in the form of NSData or NSString depending on the method you use.

<?php
    $name = "William";
    echo $name;
?>

With a parameter GET http://myserver.com/some_script.php?name=William:

<?php
    $name = $_GET['name']; // takes the ?name=William parameter from the URL
    echo $name; // William
?>

As to the Swift side of things, there is a perfectly valid answer here which denotes one of the myriad methods of sending a request: https://stackoverflow.com/a/24016254/556479.

Community
  • 1
  • 1
max_
  • 24,076
  • 39
  • 122
  • 211