In my PHP, I'm tying to send an array with data from the database. All values should be accepted as NSString exept one image that is stored as 'medium blob' in the database, and I'm trying to pass it's NSData\UIImage value.
while ($row = mysql_fetch_array($result)) {
$add = array();
$add["Id"] = $row["Id"];
$add["Mail"] = $row["Mail"];
$add["Category"] = $row["Category"];
$add["Phone"] = $row["Phone"];
$add["Msgs"] = $row["Msgs"];
//image from blob
$add["Picture"] = $row["Picture"];
// push single add into final response array
array_push($response["adds"], $add);
}
// success
$response["success"] = 1;
$response["message"] = "Adds loaded successfully";
// echoing JSON response
echo json_encode($response);
Now in Xcode, all values are received just fine except the image that is NULL. I tried to encode it with base64 in PHP and decode in Objective-C, but xcode collapses because it's still NULL. I tried to define:
header("Content-type: image/png");
or
file_put_contents("image.png", $add["Picture"]);
but it's always received as NULL. Rows that don't have blobs stored in them return as ' ', only the one with content returns NULL. I'm new to PHP, and I'm sure I'm doing some basic stupid mistake.
BTW my Objective-C code is:
const void *bytes = [[addPicture objectAtIndex:indexPath.row] bytes];
int length = [[addPicture objectAtIndex:indexPath.row] length];
NSData* imageData = [[NSData alloc] initWithBytes:bytes length:length];
aCell.cellBackImg.image = [UIImage imageWithData:imageData];
Related
how do i upload a Base64 encoded image to a PHP server using HttpURLConnection? All the answers i have seen so far are based on HttpClient which no longer exists. I got a httprequest.java library that sends post request to the server, the problem i have with it is that the image string at the server-side is always different to the one i send.
This is my code so far.
HttpRequest request = new HttpRequest(Konstants.address+Konstants.save_image);
request.prepare(HttpRequest.Method.POST);
String encodedImage = Base64.encodeToString(image, Base64.URL_SAFE);
//image is a byte[] with image data
HashMap<String, String>map = new HashMap<>();
map.put("username",username);
map.put("image", encodedImage);
Log.d("IMAGE-DATA", encodedImage);
request.withData(map);
JSONObject object = request.sendAndReadJSON();
code = object.getInt("response_code");
if (code == 0)
flag = Boolean.FALSE;
String s = object.getString("response_message");
Log.d("SERVER-REPLY", s);
//encodedImage and s are different
and the PHP code below:
<?php
if(!$_SERVER['REQUEST_METHOD']=='POST'){
$response["response_code"] = 0;
$response["response_message"] = "INVALID REQUEST";
die(json_encode($response));
}
if (empty($_POST)) {
$response["response_code"] = 0;
$response["response_message"] = "One or both of the fields are empty .";
die(json_encode($response));
}
$username1 = urldecode($_POST['username']);
$data = $_POST['image'];
$binary = base64_decode($data);
list($path, $tmp) = explode(".", $username1);
$success = file_put_contents("./images/$path.png", $binary);
if ($success){
$response["response_message"]=$data;
$response["response_code"] = 1;
}else{
$response["response_message"]="failure";
$response["response_code"] = 0;
}
echo json_encode($response);
?>
Look into the differences. Sometimes you need to replace spaces with plusses.
$binary = base64_decode(str_replace(" ", "+", $_POST['image']));
I have had quite the night trying to solve problems after "Upgrading" to OS X Yosemite 10.6.6. After re-installing MySQL / phpMyAdmin / Apache / php5 I am still having problems with code that worked before the upgrade. The following function sends a URL request to a locally hosted php file to obtain data from a MySQL data base in a JSON parable format:
-(NSArray*) GetJSONArrayForURL:(NSString*)url
{
// Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:url];
// Create the request
//NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
NSURLRequest* request = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
NSURLResponse* response = nil;
NSData *rawdata = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSMutableData *downloaded = [[NSMutableData alloc] init];
[downloaded appendData:rawdata];
// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:downloaded options:NSJSONReadingAllowFragments error:&error];
return jsonArray;
}
However, the raw data returned is the source code of the PHP file it is requesting:
<?php
$serverName = "localhost";
$databaseName = "GUESTLISTER";
$userName = $_GET['username'];
$password = $_GET['password'];
$POST = "POST";
$GET = "GET";
// Create connection
$con=mysqli_connect($serverName,$userName,$password,$databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
//$sql = "SELECT * FROM users";
$sql = $_GET['query'];
$action = $_GET['action'];
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
$id = mysqli_insert_id($con);
if($action == $GET)
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
else if ($action == $POST)
{
echo $id;
}
}
// Close connections
mysqli_close($con);
?>
The request which is:
http://localhost/webservice.php?&username=admin&password=guestlister123&query=SELECT%20*%20FROM%20users&action=GET
Runs fine when pinged from a web browser, but for some bizarre reason the source code is returned as data when requested from Xcode.
Please advise,
Ryan
Usually when the same source code is returned instead of its output, it points to the issue that Php is not getting parsed as Php. That means there is an issue with the setup for your webserver - Apache since its unable to process Php. There can be many different reasons for this, a few of them can be
Apache is off and may need to be turned on, which since outside the xcode it works then that may not be the case
Apache configuration for Php is not set up correctly
The website is not in the folder where Apache expects it to be. htdocs is usually the default where Apache looks for php scripts depending on the php.ini configuration. A quickest way is to run the phpinfo(); in a php file between the starting and ending php tags to determine if all is well with your setup.
phpinfo();
If its set up correctly you would see an output page with all the information about your php and apache setup else it will just give you back the phpinfo() line as output. Finally it could just be that Xcode is not working properly with your Apache setup thus it can be beneficial to directly run scripts through the browser instead of within Xcode which I have never tried.
The goal is to display a result of json_encode result from php into swift as a label. I have referenced to many tutorials and practices of parsing json with swift, but I still cant understand the issue.
I referenced to an example that uses date.jsontest.com and that works fine.
In my project, I have parsed this simple JSON object to start:
[{"username":"user"}]
Here is the swift code:
override func viewDidLoad() {
super.viewDidLoad()
// 1
//let urlAsString = "http://date.jsontest.com"
let urlAsString = "http://(ip address)/service.php"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
// 2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
println(error.localizedDescription)
}
var err: NSError?
// 3
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
// 4
//let jsonDate: String! = jsonResult["date"] as NSString
//let jsonId = jsonResult["id"] as NSString
//let jsonTime: String! = jsonResult["time"] as NSString
let jsonUser: String! = jsonResult[0] as NSString
dispatch_async(dispatch_get_main_queue(), {
//self.dateLabel.text = jsonId
//self.timeLabel.text = jsonUser
self.dateLabel.text = jsonUser
})
})
// 5
jsonQuery.resume()
//searchItunesFor("JQ Software")
//startConnection()
// Do any additional setup after loading the view, typically from a nib.
}
The code runs fine when I use http://date.jsontest.com as the string along with jsonDate and jsonTime.
I tried to understand the debugger in Xcode, but as a new user to Swift, its hard to understand what the issue is. All I could root out is that there is an issue with how my JSON is formatted.
Any tips are greatly appreciated, thanks.
EDIT:
Here is the code http://(ip address)/service.php that gives me the JSON
<?php
//connect to MySQL
// Create connection
$con=mysqli_connect($hostname,$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT username FROM members WHERE id = 1";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
I am a beginner to iOS. I have a simple web service that retrieves data from a table and sends out the results in JSON. I am trying to communicate with that web service from iOS to receive the JSON response but facing issues. This is the error i receive:
Request Failed with Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(
"text/json",
"application/json",
"text/javascript"
)}, got text/html" UserInfo=0x7598e70
Here are my code snippets:
PHP Web Service:
$stmt = "SELECT STORE_TYPE, STORE_NAME FROM STORE WHERE STORE_ZIP = $zip";
$result = mysqli_query($this->databaseconnection, $stmt);
$storelist = array();
$store = array();
$jsondata;
while ($row = mysqli_fetch_assoc($result)) {
$store['STORE_TYPE'] = $row['STORE_TYPE'];
$store['STORE_NAME'] = $row['STORE_NAME'];
array_push($storelist,$store);
}
$jsondata = json_encode($storelist);
echo $jsondata;
I am getting the following result when i execute my php form the browser:
[{"STORE_TYPE":"GROCERY","STORE_NAME":"Walmart"},{"STORE_TYPE":"BAKERY","STORE_NAME":"Lanes Bakery"},{"STORE_TYPE":"GROCERY","STORE_NAME":"Copps"}]
iOS Code Snippet to communicate with the Web Service:
NSURL *url = [NSURL URLWithString:#"http://localhost/~Sandeep/store/store.php?rquest=getstores&zip=53715"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"%#", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
I looked at a lot of tutorials and they all say that performing a 'json_encode' on an array in php encodes the data in JSON format and 'echo' of that is the way to go send the encoded JSON as a response. For some reason my iOS is not seeing that as JSON. I am not sure what I am missing/doing wrong here.
I really appreciate your inputs on this.
Thanks!
You need to set the correct content type(use header), the error lists the acceptable types though you should use application/json
$stmt = "SELECT STORE_TYPE, STORE_NAME FROM STORE WHERE STORE_ZIP = $zip";
$result = mysqli_query($this->databaseconnection, $stmt);
$storelist = array();
$store = array();
$jsondata;
while ($row = mysqli_fetch_assoc($result)) {
$store['STORE_TYPE'] = $row['STORE_TYPE'];
$store['STORE_NAME'] = $row['STORE_NAME'];
array_push($storelist,$store);
}
$jsondata = json_encode($storelist);
header('Content-Type: application/json');
echo $jsondata;
I'am developing an iPhone application to display data from php. Data are obtained from a Mysql database then encoded to JSON format in php file:
include_once 'connectionIncl.php';
if(function_exists($_GET['method'])){
$_GET['method']();
}
function getSQLIntoJSONFormat()
{
$arr;
$sql = mysql_query("SELECT * FROM pecivo");
while($pecivo = mysql_fetch_assoc($sql)){
$arr[] = $pecivo['typ'];
}
$arr= json_encode($arr);
echo $_GET['jsoncallback'].'('.$arr.')';
}
// --- http://127.0.0.1:8887/TeplyRohlik/pecivo.php?method=getSQLIntoJSONFormat&jsoncallback=?
when i run this from browser, it returns correct data :
(["sejra","knir","baba","vousy","sporitelna25"])
Also, on iOS a have this code:
NSString * urlString = [NSString stringWithFormat:#"http://192.168.0.10:8887/TeplyRohlik/pecivo.php?method=getSQLIntoJSONFormat&jsoncallback=?"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",json);
And result is .... (null).
I have no idea how to get this working...
It looks like your PHP method is spitting out JSONP. What you probably want to do is change that to:
function getSQLIntoJSONFormat()
{
$arr;
$sql = mysql_query("SELECT * FROM pecivo");
while($pecivo = mysql_fetch_assoc($sql)){
$arr[] = $pecivo['typ'];
}
$arr= json_encode($arr);
echo $arr;
}
You are seeing the output be wrapped in parentheses as it's expecting a GET parameter in the request called jsoncallback which would make the output look something like this:
javascriptFunction(["a","b","b"])
That's not what you want on your iOS device. You want just the raw JSON string of the array, no wrapping in a callback function call.