Swift 2, uploading base64 images to PHP - php

I'm having a huge issue trying to upload my images to php.
my script works fine but when I go to view the image online it shows a broken image and if I download it and try to open in photoshop it says the image is corrupt.
Swift file upload script
func percentEscapeString(string: String) -> String {
return CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
string,
nil,
":/?#!$&'()*+,;=",
CFStringBuiltInEncodings.UTF8.rawValue) as String;
}
func imagePost(params : NSMutableDictionary, image: UIImage, url: String, postCompleted: (succeeded: Bool, msg: AnyObject) -> ()){
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let imageData = UIImageJPEGRepresentation(image, 0.9)
var base64String = self.percentEscapeString(imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))) // encode the image
print(base64String)
params["image"] = [ "content_type": "image/jpeg", "filename":"test.jpg", "file_data": base64String]
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions(rawValue: 0))
}catch{
print(error)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
NSOperationQueue.mainQueue().addOperationWithBlock {
var err: NSError?
var json:NSDictionary?
do{
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
}catch{
print(error)
err = error as NSError
}
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData!)")
print(err!.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
postCompleted(succeeded: false, msg: "Error")
}else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
if let success = parseJSON["success"] as? Bool {
//print("Success: \(success)")
postCompleted(succeeded: success, msg: parseJSON["message"]!)
}
return
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
postCompleted(succeeded: false, msg: "Unable to connect")
}
}
}
})
task.resume()
}
PHP script
$json = file_get_contents('php://input');
$obj = json_decode($json);
if($obj->image->content_type == "image/jpeg"){
$filename = $obj->id . time() . ".jpg";
$target_file = "userImages/$filename";
if(file_put_contents($target_file, $obj->image->file_data)){
$return_data = ["success"=>true, "message"=>"The photo has been uploaded."];
} else {
$return_data = ["success"=>false, "message"=>"Sorry, there was an error uploading your photo."];
}
}else{
$return_data = ["success"=>false,"message"=>"Not a JPEG image"];
}
part of the base64 before uploading.
%2F9j%2F4AAQSkZJRgABAQAASABIAAD%2F4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAlqADAAQAAAABAAAAyAAAAAD%2F7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs%2BEJ%2B%2F8AAEQgAyACWAwEiAAIRAQMRAf
part of the base64 after uploading.
%2F9j%2F4AAQSkZJRgABAQAASABIAAD%2F4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAlqADAAQAAAABAAAAyAAAAAD%2F7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs%2BEJ%2B%2F8AAEQgAyACWAwEiAAIRAQMRAf
Can anyone see any problems?

It seems that this code for replacing unwanted characters in the base64 doesn't work for php.
func percentEscapeString(string: String) -> String {
return CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
string,
nil,
":/?#!$&'()*+,;=",
CFStringBuiltInEncodings.UTF8.rawValue) as String;
}
I took it out and altered my php code to replace the unwanted characters.
if($obj->image->content_type == "image/jpeg"){
$filename = $obj->id . time() . ".jpg";
$target_file = "userImages/$filename";
$data = str_replace(' ', '+', $obj->image->file_data);
$data = base64_decode($data);
if(file_put_contents($target_file, $data)){
$return_data = ["success"=>true, "message"=>"The photo has been uploaded."];
} else {
$return_data = ["success"=>false, "message"=>"Sorry, there was an error uploading your photo."];
}
}else{
$return_data = ["success"=>false,"message"=>"Not a JPEG image"];
}
This fixed it for me.

|*| Swift2 Code : To Convert Image to String for sending to Php Server
let NamImjVar = UIImage(named: "NamImjFyl")
let ImjDtaVar = UIImageJPEGRepresentation(NamImjVar!, 1)
let ImjSrgVar = ImjDtaVar!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue:0))
|*| Php Code : To Convert String data back to image and save in server
<?php
$NamImjSrgVar = $_REQUEST["ImjKey"];
header('Content-Type: image/jpeg');
$NamImjDtaVar = str_replace(' ', '+', $NamImjSrgVar);
$NamImjHexVar = base64_decode($NamImjDtaVar);
file_put_contents("NamFyl.jpg", $NamImjHexVar)
?>

Related

Xcode Swift/PHP/SQL upload multiple images failed

I am learning "posting images to server", but when I tried the multiple images uploading, it always failed with reporting(JSON error, from my Xcode alert on iOS devices), it seems error is in the PHP side? But I am new, so anyone can help me to find any solution.
Xcode:
httpBody function
func createBodyWithParameters(parameters: [String : Any]?,boundary: String) -> NSData {
let body = NSMutableData()
if parameters != nil {
for (key, value) in parameters! {
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!)
body.append("\(value)\r\n".data(using: .utf8)!)
}
}
for image in images {
let filename = "\(NSUUID().uuidString).jpg"
let imageData = image.jpegData(compressionQuality: 1)
let lineOne = "--" + boundary + "\r\n"
body.append(lineOne.data(using: .utf8, allowLossyConversion: false)!)
let lineTwo = "Content-Disposition: form-data; name=\"files\"; filename=\"\(filename)\"\r\n"
body.append(lineTwo.data(using: .utf8, allowLossyConversion: false)!)
let lineThree = "Content-Type: image/jpg\r\n\r\n"
body.append(lineThree.data(using: .utf8, allowLossyConversion: false)!)
body.append(imageData!)
let lineFive = "\r\n"
body.append(lineFive.data(using: .utf8, allowLossyConversion: false)!)
}
let lineSix = "--" + boundary + "--\r\n"
body.append(lineSix.data(using: .utf8, allowLossyConversion: false)!)
return body
}
http request function
func createRequest(parameters: [String : Any] , url : URL) -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = "POST"
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpBody = createBodyWithParameters(parameters: parameters, boundary: boundary) as Data
return request
}
multi images upload functions
func uploadPostWithMultipleImages() {
guard let id = currentUser?["id"], let text = postTextView.text else {
return
}
// declaring keys and values to be sent to the server
let parameters = ["user_id": id, "text": text, "files": images]
// declaring URL and request
let url = URL(string: "http://localhost/projectExample/uploadPostMultipleImages.php")!
let request = createRequest(parameters: parameters, url: url)
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
// if error
if error != nil {
Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
return
}
// access data / json
do {
// safe mode of accessing received data from the server
guard let data = data else {
Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self)
return
}
// converting data to JSON
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
// safe mode of accessing / casting JSON
guard let parsedJSON = json else {
return
}
// if post is uploaded successfully -> come back to HomeVC, else -> show error message
if parsedJSON["status"] as! String == "200" {
// post notification in order to update the posts of the user in other viewControllers
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "uploadPost"), object: nil)
// comeback
self.dismiss(animated: true, completion: nil)
} else {
Helper().showAlert(title: "Error", message: parsedJSON["message"] as! String, in: self)
return
}
// error while accessing data / json
} catch {
Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
return
}
}
}.resume()
}
PHP upload code
// generating absolute path to the folder for every user with his unique id
$folder = '/Applications/XAMPP/xamppfiles/htdocs/projectExample/posts/' . $user_id;
// creating fodler if it doesn't exist
if (!file_exists($folder)) {
mkdir($folder, 0777, true);
} else {
$return['folder_message'] = 'Could not create a directory';
}
foreach($_FILES['files']['name'] as $key =>$value) {
$file = $_FILES['files']['name'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
// path to the file. Full path of the file
$path = $folder . '/' . basename($file);
if (move_uploaded_file($file_tmp, $path)) {
// creating URL link to the image uploaded
$pictures .= 'http://localhost/projectExample/posts/' . $user_id . '/' . $file. " ";
$return['pictures'] = $pictures;
}
}//foreach
// Insert details into database
$result = $access->insertPost($user_id, $text, $pictures);
I use your swift code and upload images successfully, so I am sure it's your PHP code that has some error. please make sure that you have return a json that is correctly-formatted like :
echo '{"code" : 200}'

File uploading but name is empty

I have an IOS app that uses PHP for my API. My file upload is working fine but the name of the file is not appending to the file. I've mirrored other pages in my app but it's still not working although others are working fine. I’m able to see the file on the server, but the name is notes-.jpg. It’s not appending the puuid to the name per the code. I've implemented MessageKit on the ViewController that isn't working (just in case it makes a difference). Here is my code below, I feel like I'm looking for a needle in a haystack. The code is a little sloppy (please don't judge).
func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
// if file is not selected, it will not upload a file to server, because we did not declare a name file
var filename = ""
if imageSelected == true {
filename = "notes-\(puuid).jpg"
print("name of file", filename)
}
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body as Data
}
func uploadImage(_ image: UIImage, completion: #escaping (URL?) -> Void) {
print("im in upload")
let avame = user!["ava"]
let user_id = user!["id"] as! String
let me = user!["username"] as! String
let recipientfe = getmessages["recipient"]
let uuidfe = getmessages["uuid"] as! String
let recipient = getmessages["username"] as! String
let rid = String(describing: getmessages["sender_id"]!)
let puuid = UUID().uuidString
let text = ""
let url = URL(string: "https://localhost/messagepost.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters = ["sender_id": user_id, "uuid": uuidfe, "sender": me, "recipient_id": rid, "recipient": recipient, "puuid": puuid, "text": text]
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
if image != nil {
data = image.jpegData(compressionQuality: 0.5)!
}
request.httpBody = createBodyWithParams(parameters, filePathKey: "file", imageDataKey: data, boundary: boundary)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error != nil {
Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
print("Server Error")
return
}
do {
guard let data = data else {
Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self)
print("Data Error")
return
}
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
guard let parsedJSON = json else {
return
}
if parsedJSON["status"] as! String == "200" {
let newurl = parsedJSON["path"]
self.isSendingPhoto = true
guard let url = newurl else {
return
}
var message = Message(messageuser: self.sender, image: image)
message.downloadURL = url as? URL
self.save(message)
self.messagesCollectionView.scrollToBottom()
} else {
if parsedJSON["message"] != nil {
let message = parsedJSON["message"] as! String
Helper().showAlert(title: "Error", message: message, in: self)
print("where am i", parsedJSON["message"] as Any)
}
}
} catch {
Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
print("where am i 2")
}
})
}.resume()
}
PHP Upload File
<?php
if (!empty($_REQUEST["uuid"])) {
$id = htmlentities($_REQUEST["id"]);
$recipient = htmlentities($_REQUEST["recipient"]);
$recipient_id = htmlentities($_REQUEST["recipient_id"]);
$uuid = htmlentities($_REQUEST["uuid"]);
$puuid = htmlentities($_REQUEST["puuid"]);
$text = htmlentities($_REQUEST["text"]);
$sender = htmlentities($_REQUEST["sender"]);
$sender_id = htmlentities($_REQUEST["sender_id"]);
if (isset($_FILES['file']) && $_FILES['file']['size'] > 1) {
$folder = "/home/xxxxx/public_html/notes/" . $uuid;
// if no posts folder, create it
if (!file_exists($folder)) {
mkdir($folder, 0777, true);
}
$picture = $folder . "/" . basename($_FILES["file"]["name"]);
chmod($picture,0777);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $picture)) {
$path = "http://localhost/notes/" . $uuid . "/notes-" . $puuid . ".jpg";
$returnArray["message"] = "Post has been made with picture";
$returnArray["path"] = $path;
$returnArray["status"] = "200";
} else {
$returnArray["message"] = "Post has been made without picture";
$path = "";
}
$result=$access->insertMessage($recipient, $recipient_id, $uuid, $sender,$sender_id, $text, $path);
// STEP 2.5 If posts are found, append them to $returnArray
if (!empty($result)) {
$returnArray["message"] = $result;
$result = $access->updatebadge($recipient_id);
}
else {
$returnArray["message"] = "Couldnt insert". $puuid ."";
}
// if data is not passed - show posts except id of the user
}
else {
$username = htmlentities($_REQUEST["username"]);
$uuid = htmlentities($_REQUEST["uuid"]);
$recipient_id = htmlentities($_REQUEST["recipient_id"]);
$message = $access->conversation($username, $uuid, $recipient_id);
if (!empty($message)) {
$returnArray["message"] = $message;
}
}
}
$access->disconnect();
echo json_encode($returnArray);
?>
I figured it out. The body and headers in Swift were incorrect and weren't sending the correct file name.
I changed the body to:
// web development and MIME Type of passing information to the web server
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// access / convert image to Data for sending to the server
var data = Data()
// if picture has been selected, compress the picture before sending to the server
if image != nil {
data = image.jpegData(compressionQuality: 0.5)!
}
// building the full body along with the string, text, file parameters
request.httpBody = Helper().body(with: parameters, filename: "notes-\(puuid).jpg", filePathKey: "file", imageDataKey: data, boundary: boundary) as Data

Data does not being sent to Database because it cannot be read

I'm working on a project where I need to send some data to the remote database. So I'm developing an iOS app using Swift 3.1 and when I try to send data to the database it says,
The data couldn’t be read because it isn’t in the correct format.
Also there is another error;
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
This is my swift code:
let urlOfSMARTCF = URL(string: "http://192.168.1.99/insertData.php")
let request = NSMutableURLRequest(url: urlOfSMARTCF! as URL)
request.httpMethod="POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
for contact in contactsCaptuure
{
let userMobileNumber = DBManager.shared.retriveRegisteredNumberOfMobile()
let postParameters = "{\"usermobilenum\":\(String(describing: userMobileNumber!)),\"contactnum\":\(contact.phoneNumber!)}";
request.httpBody = postParameters.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest)
{
data, response, error in
if error != nil
{
print("error is \(String(describing: error))")
return;
}
do
{
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = myJSON
{
var msg : String!
msg = parseJSON["message"] as! String?
print(msg)
}
}
catch
{
print(error.localizedDescription)
print(error)
}
}
print("Done")
task.resume()
}
This is my PHP in remote database:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
require 'connectDB.php';
$userPhone = $_POST["usermobilenum"];
$contactNum = $_POST["contactnum"];
$query = "SELECT * FROM user WHERE UserMobNum='".$userPhone."'"; // Usermobile is registered.SIP exists.
if($results= mysqli_query($connect,$query))
{
if(mysqli_num_rows($results)>0)
{
$i=0;
while($rows=mysqli_fetch_assoc($results))
{
$sip[$i] = $rows["SIP"];
$i++;
}
$queryToAddData = "INSERT INTO user (UserMobNum,SIP,Phone) VALUES ('".$userPhone."','".$sip[0]."','".$contactNum."')";
if(mysqli_query($connect,$queryToAddData))
{
//Return success message to the app
echo "Success"
}
else
{
die(mysqli_error($connect));
}
}
else
{
$availableSIP=false;
while($availableSIP==false) // Assign a random value until it's being a valid one.
{
$sip[0]=rand(1,9999);
$queryToCheck = "SELECT * FROM user WHERE SIP='".$sip[0]."'";
if($results= mysqli_query($connect,$queryToCheck))
{
if(mysqli_num_rows($results)==0)
{
$availableSIP=true;
}
}
}
$queryToAddData = "INSERT INTO user (UserMobNum,SIP,Phone) VALUES ('".$userPhone."','".$sip[0]."','".$contactNum."')";
if(mysqli_query($connect,$queryToAddData))
{
//Return success message to the app
echo "Success"
}
else
{
die(mysqli_error($connect));
}
}
}
else
{
echo "First Level Failure!";
die(mysqli_error($connect));
}
mysqli_close($connect);
}
else
{
echo "Failed in POST Method"
}
?>
What I did
Went through all of stack overflow and other site suggestions but had no luck. I even checked my jSon string using a json validator and it passed. This is how my jSon string looks like.
{"usermobilenum":1234567890,"contactnum":9345}
However after some search I found that this happens because Remote database PHP sends this error message. So I checked each and every variable in PHP but couldn't find any problem. Also this couldn't be a problem with PHP cause I work with those exact php files when I connect to via my android app. That works fine. But in iOS it generates that error. Can someone help me please?
UPDATE
This is insertdataTest.php file:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$userPhone = $_POST["usermobilenum"];
echo $userPhone;
mysqli_close($connect);
}
else
{
echo json_encode("Failed in POST Method");
}
?>
{"usermobilenum":1234567890,"contactnum": 9345} - this is treated as a String. It's not a VALID JSON.
Updated code:
let urlOfSMARTCF = URL(string: "http://192.168.1.99/insertData.php")
let request = NSMutableURLRequest(url: urlOfSMARTCF! as URL)
request.httpMethod="POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
for contact in contactsCaptuure {
let userMobileNumber = DBManager.shared.retriveRegisteredNumberOfMobile()
let postParameters = NSMutableDictionary()
postParameters["usermobilenum"] = userMobileNumber
postParameters["contactnum"] = contact.phoneNumber!
let jsonData = try? JSONSerialization.data(withJSONObject: postParameters, options: .prettyPrinted)
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error is \(String(describing: error))")
return;
}
do {
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]
if let parseJSON: NSMutableDictionary = NSMutableDictionary(dictionary: myJSON as! NSMutableDictionary){
let msg = parseJSON["message"] as! String
print(msg)
}
}
catch {
print(error.localizedDescription)
print(error)
}
}
print("Done")
task.resume()
}
Buddy I debug you code and found that there is error in server response not in you code. try this and reply me ASAP please
before this line "let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary"
add "let str = String.init(data: data!, encoding: .utf8)
print(str ?? "error")"
I am waiting please.

Why is this JSON refusing to get a response? And fails on a curl http://.... response.json command

I am having trouble getting this JSON to output correctly. I have been struggling with this for a number of days now.
The initial error I was receiving was:
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
This is the output in the browser I get when using the request:
http://www.quasisquest.uk/KeepScore/getTotalsStats.php?player_id=2
{"Stats":{"totalWins":10,"totalDraws":6,"totalLosses":3,"winPercentage":"52.63%","goalsScored":40,"goalsConceded":30,"goalDifference":10}}
After discussion on here it was mentioned the problem may be php side but I am at a loss to what since even a simple echo json_endcode ("test") and taking out any MySQL interference has not worked.
I have spoke my to hosting company who have said everything is fine server-side.
This is the Swift function:
override func viewDidAppear(_ animated: Bool)
{
//communitiesTableView.reloadData()
let isUserLoggedIn = UserDefaults.bool(UserDefaults.standard)(forKey: "isUserLoggedIn");
if(!isUserLoggedIn)
{
self.performSegue(withIdentifier: "loginView", sender: self);
}
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getTotalsStats.php?");
var request = URLRequest(url:myUrl!);
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.httpMethod = "POST";
let postString = "player_id=\(self.playerId)";
request.httpBody = postString.data(using: String.Encoding.utf8);
print (myUrl!,postString)
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if error != nil {
print("error=\(error)")
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? AnyObject
print (json!)
if let arr = json?["Stats"] as? [[String:AnyObject]] {
self.totalWins = arr.flatMap { $0["totalWins"]}
print("here: ", self.totalWins)
}
} catch{
print(error)
}
}
}
task.resume()
}
Below is the php script:
<?php
require ("Conn.php");
require ("MySQLDao.php");
$playerId = htmlentities($_REQUEST["player_id"]);
$returnValue = array();
if(empty($playerId))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$dao = new MySQLDao();
$dao->openConnection();
//WINS LOSSES DRAWS AND %
$playerTotalWins = array();
$playerTotalWins = $dao->getTotalWins($playerId);
$playerTotalDraws = array();
$playerTotalDraws = $dao->getTotalDraws($playerId);
$playerTotalLosses = array();
$playerTotalLosses = $dao->getTotalLosses($playerId);
$winPercentage = (($playerTotalWins) / (($playerTotalWins) + ($playerTotalDraws) + ($playerTotalLosses)));
$newWinpercent = sprintf("%.2f%%", $winPercentage* 100);
//GOALS SCORED
$goalsScoredHome = array();
$goalsScoredHome = $dao->getGFHome($playerId);
$goalsScoredAway = array();
$goalsScoredAway = $dao->getGFAway($playerId);
$totalGoalsScored = ($goalsScoredHome + $goalsScoredAway);
//GOALS CONCEDED
$goalsConcededHome = array();
$goalsConcededHome = $dao->getGCHome($playerId);
$goalsConcededAway = array();
$goalsConcededAway = $dao->getGCAway($playerId);
$totalGoalsConceded = ($goalsConcededHome + $goalsConcededAway);
//GOAL DIFFERENCE
$goalDifference = ($totalGoalsScored - $totalGoalsConceded);
//PRINT OUT
header('Content-Type: application/json');
$arr = array('totalWins' => $playerTotalWins, 'totalDraws' => $playerTotalDraws, 'totalLosses' => $playerTotalLosses, 'winPercentage' => $newWinpercent, 'goalsScored'=>$totalGoalsScored, 'goalsConceded'=>$totalGoalsConceded, 'goalDifference' => $goalDifference);
echo json_encode (array('Stats' => $arr));
$dao -> closeConnection();
?>
It has been suggested I run a curl http://... -> response.json but this seems to save a file with 0 bytes.
I am totally at a loss and new to Swift so all help is appreciated.
So the problem was in this line let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getTotalsStats.php?"); The ? was kicking it out.
Solved :)

Image is not uploaded in PHP using Swift

I am trying to use Google Vision API and upload an image using their API to get analysis. I am using this php code:
<?php
include("./includes/common.php");
include_once("creds.php"); // Get $api_key
$cvurl = "https://vision.googleapis.com/v1/images:annotate?key=" . $api_key;
$type = "LABEL_DETECTION";
//echo "Item is: " . $item;
//Did they upload a file...
$item = $_GET[item];
if($_FILES['photo']['name'])
{
}else{
echo "you did not upload image".
}
It always show "you did not upload image". And here's my Swift function where I upload the image:
func UploadRequest(img: UIImage, item: String)
{
let url = NSURL(string: "http://myurlhere")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let boundary = generateBoundaryString()
//define the multipart request type
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let image_data = UIImagePNGRepresentation(img)
if(image_data == nil)
{
return
}
let body = NSMutableData()
let fname = "image.png"
let mimetype = "image/png"
//define the data post parameter
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition:form-data; name=\"test\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("hi\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(image_data!)
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
//EZLoadingActivity.hide(success: false, animated: true)
print("error")
return
}
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(dataString)
//EZLoadingActivity.hide(success: true, animated: true)
self.dismissViewControllerAnimated(true, completion: nil)
}
task.resume()
}
When I do print_r($_FILES), I get:
Array
(
[file] => Array
(
[name] => image.png
[type] => image/png
[tmp_name] => /tmp/phplSB2dc
[error] => 0
[size] => 864781
)
)
Your form data is currently submitting:
body.appendData("Content-Disposition:form-data; name=\"file\";...
And according to your print_r($_FILES), you should be using file instead of photo:
$_FILES['file']['name']
Also, you should be checking to make sure the file uploaded correctly using:
if ( $_FILES['file']['error'] == UPLOAD_ERR_OK )
{
//File uploaded correctly
}
func uploadMultipleIMAGE( APIStriing:NSString, dataString:NSString) -> Void
{
//Here dataString is image binary data just append you your url and just pass the image it will handle.
print("wscall URL string \(APIStriing)")
print("Data string URL string \(dataString)")
let postData = dataString.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!
let postLength = "\(UInt(postData.length))"
let request = NSMutableURLRequest()
request.URL = NSURL(string: APIStriing as String)!
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?,data: NSData?,error: NSError?) -> Void in
if error == nil {
print("success")
}
else {
let alert = UIAlertView(title: "Sorry For Inconvenience ", message: "Contact to Administration", delegate: self, cancelButtonTitle: "Ok")
alert.show()
}
})
}
Note:- when you convert image to binary data you need to handle special character. here you can handle special character. follow this step.
1.
let imgData = UIImagePNGRepresentation(image)
imgBase64String = imgData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
var newimagdat = NSString()
newimagdat = newimagdat.stringByAppendingString(self.percentEscapeString(imgBase64String) as String)
imgarray.addObject(newimagdat)
Create character handler class something like that.
class handlecharacter: NSCharacterSet {
func urlParameterValueCharacterSet() -> NSCharacterSet {
let characterser = NSMutableCharacterSet.alphanumericCharacterSet()
characterser.addCharactersInString("-._~")
return characterser
}
}
Now create function your class where you want to upload images
func percentEscapeString(imgstring:NSString) -> NSString
{
let handle = handlecharacter()
return imgstring.stringByAddingPercentEncodingWithAllowedCharacters(handle.urlParameterValueCharacterSet())!
}

Categories