I'm trying to upload an image to my localhost Sever and saving the path to a database. I already have some other code, where I upload a new Object. Is it possible to upload the image in the same function as shown below. I have not found any good tutorials on how to do this with other uploads in the same function (in the same sql request). The Spot
object has an element image, which is the UIImage
, that has to be uploaded.
The Swift code:
if let url = URL(string: "http://localhost:8080/add.php") {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.timeoutInterval = 20.0
var dataString = "secretWord=235ghzjg35" // starting POST string with a secretWord
dataString = dataString + "&name=\(spot.name!)"
dataString = dataString + "&lat=\(spot.lat!)"
dataString = dataString + "&long=\(spot.long!)"
let dataD = dataString.data(using: .utf8)
do{
let uploadJob = URLSession.shared.uploadTask(with: request, from: dataD) { data, response, error in
if error != nil {
DispatchQueue.main.async {
print("No connection")
}
}
else {
if let unwrappedData = data {
let returnedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
if returnedData == "1"{
DispatchQueue.main.async {
print("Upload completed")
}
}
else {
DispatchQueue.main.async {
print(returnedData ?? "no data back'")
}
}
}
}
}
uploadJob.resume()
}
}
The Php code:
<?php
$secret = $_POST["secretWord"];
if ("235ghzjg35" != $secret) exit;
$name = $_POST["name"];
$lat = $_POST["lat"];
$long = $_POST["long"];
//$img0 = $_FILES['img0'];
//$target0 = "spotImages/" . $name;
//$target0 = $target0 . basename($img0);
// Create connection
$con=mysqli_connect("localhost", "user", "pass", "db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//then adding here the image
$sql = "INSERT INTO `table` (`id`, `name`, `long`, `lat`) VALUES (NULL, '". $name ."', '". $long ."', '". $lat ."');";
$result = mysqli_query($con, $sql);
echo $result;
mysqli_close($con);?>
Furthermore I wanted to know if there are any better solutions on how to manage a Database with Swift for my App. I have read some things about Firebase and Realm.io. Has anyone had any experiences? And if so, what are the pros and cons? Should I consider using that instead of my approach?