I'm recently trying to send an NSArray of integers to my server that runs PHP. If this succeeds, the server will then proceed the data. So I need a way to send the array properly to php and than transform the array so that php can work with it.
This is my Swift-Code for sending the array so far:
let url = NSURL(string: urlPathWithPathAndPHPExtension("---"))!
var session: NSURLSession!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
do {
dataNotice = try context.executeFetchRequest(fetchRequestForNotice) as! [Notice]
} catch {
print(error)
}
let postString = "server=\(server)&username=\(username)&password=\(password)&database=\(database)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithRequest(request)
task.resume()
Like I said till now I couldn't discover a way to receive the array in the right way on the PHP-Side. Please can you help me?
Many thanks in advance!
UPDATE
Ok now I implemented the JSON-Encoding-Method in my class. But unfortunately the debugger throws an error and now I don't know if I pass the data correctly to the server.
Error:
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
Here is my updated code:
let url = NSURL(string: urlPathWithPathAndPHPExtension("---"))!
var session: NSURLSession!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
do {
dataNotice = try context.executeFetchRequest(fetchRequestForNotice) as! [Notice]
} catch {
print(error)
}
//create array of existing IDs
var noticeIDs: [String:Int] = NSDictionary() as! [String : Int]
for var i = 0; i < dataNotice.count; i++ {
noticeIDs[String(i)] = Int(dataNotice[i].id!)
}
do {
let jsonIdArray = try NSJSONSerialization.dataWithJSONObject(noticeIDs, options: NSJSONWritingOptions.PrettyPrinted)
let postString = "server=\(server)&username=\(username)&password=\(password)&database=\(database)&countOfIDs=\(dataNotice.count)¬iceIDs=\(jsonIdArray)"
print(postString)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithRequest(request)
task.resume()
} catch {
print(error)
}
And here is the server side (PHP):
<?php
$method = $_POST['method'];
$db_server = $_POST['server'];
$db_benutzer = $_POST['username'];
$db_passwort = $_POST['password'];
$db_name = $_POST['database'];
$countOfIDs = $_POST['countOfIDs'];
$json = file_get_contents('php://input');
$noticeIDs = json_decode($json);
$con=mysqli_connect($db_server,$db_benutzer,$db_passwort,$db_name);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Notice`";
$sqlID = "SELECT `ID` FROM `Notice`";
if ($result = mysqli_query($con, $sql)) {
if ($resultID = mysqli_query($con, $sqlID)) {
$resultArray = array();
$tempArray = array();
$idArray = array();
$tempIDArray = array();
while($rowID = $resultID->fetch_object())
{
$tempIDArray = intval($rowID->ID);
array_push($idArray, $tempIDArray);
}
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
$applicationIDs = array();
$finalSql = "SELECT * FROM `Notice`";
if ($countOfIDs > 0) {
for ($i = 0; $i < $countOfIDs; $i++) {
$index = $noticeIDs(strval($i));
$index = intval($index);
array_push($applicationIDs, $index);
}
$neededNotices = array_diff($idArray, $applicationIDs);
$array = array_map('intval', $neededNotices);
$array = implode("','",$array);
$finalSql = "SELECT * FROM `Notice` WHERE `ID` IN ('".$array."')";
}
if ($finalResult = mysqli_query($con, $finalSql)) {
$finalArray = array();
$tempFinalArray = array();
while($finalRow = $finalResult->fetch_object())
{
$tempFinalArray = $finalRow;
array_push($finalArray, $tempFinalArray);
}
echo json_encode($finalArray);
}
}
}
mysqli_close($con);
?>
The idea behind the code is, that the Server compares the ID's of the objects inside the app database and the ID's of the objects inside my server database. Only the non-redundant objects will be returned from the code. The code works if I initialise a test array within PHP with several integers inside it...
How can I achieve that?