3

what i've to do for getting, posting and checking data from a DB (MySQL) using swift? Can I only create the php pages and contact them or there's a way to manage them? If yes, how?

1 Answer 1

7

(Sorry for my english)

Yes you need a php script

In your swift file:

var bodyData = "name=value" //To get them in php: $_POST['name']


    let URL: NSURL = NSURL(string: "URL TO YOUR PHP FILE")
    let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
    request.HTTPMethod = "POST"
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
    {
            (response, data, error) in
            var output = NSString(data: data, encoding: NSUTF8StringEncoding) // new output variable
            var array = self.JSONParseArray(output)
    }

in php:

function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
    $status_header = 'HTTP/1.1 ' . $status;
    header($status_header);
    header('Content-type: ' . $content_type);
    echo $body;
}

$name = $_POST['name']; // Like in the bodyData var

//Doing sql things

$result = array(
    "result" => "VARIABLE TO SEND BACK"
);


sendResponse(200, json_encode($result));

And if you wan't to get the result in an array use this function:

func JSONParseArray(jsonString: String) -> Array<String> {
    var e: NSError?
    var data: NSData!=jsonString.dataUsingEncoding(NSUTF8StringEncoding)
    var jsonObj = NSJSONSerialization.JSONObjectWithData(
        data,
        options: NSJSONReadingOptions(0),
        error: &e) as Array<String>
    if e == 0 {
        return Array<String>()
    } else {
        return jsonObj
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

How the third code works? i get an error at this point var jsonObj = NSJSONSerialization.JSONObjectWithData( data, options: NSJSONReadingOptions(0), error: &e) as Array<String> fatal error: unexpectedly found nil while unwrapping an Optional value
You need to give the output to this function and it return it back but in a array
Look at the first code i have updated it check the output and array variable
Did you try: var array = self.JSONParseArray(output) (With the self.)
What beta version of xCode do you have?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.