Pietro La Spada
Pietro La Spada

Reputation: 897

MySQL online DB access in swift

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?

Upvotes: 3

Views: 8038

Answers (1)

Clement Bisaillon
Clement Bisaillon

Reputation: 5177

(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
    }
}

Upvotes: 7

Related Questions