Now I'm trying to POST jpeg files to MySQL via PHP and GET from MySQL to iOS.
In GET method I encode jpeg(as NSData) and some related data(ex. caption, timestamp) to JSON on PHP script using json_encode().
{"caption":"(captiondata)","img":"(imagedata)","timestamp":"(timestampdata)"}
Then I set the datas into array like,
[{"caption":"(captiondata)","img":"(imagedata)","timestamp":"(timestampdata)"},
{"caption":"(captiondata)","img":"(imagedata)","timestamp":"(timestampdata)"},
.......,
{"caption":"(captiondata)","img":"(imagedata)","timestamp":"(timestampdata)"}]
I believe I can parse and get this JSON by echo (json_encode ()) on PHP and SBJsonParser on iOS but nothing returns to my App. Here's my code in iOS.(Also I use TTURLRequest by Three20)
TTURLRequest* request = [TTURLRequest requestWithURL:url delegate:self];
request.cachePolicy = cachePolicy;
TTURLJSONResponse* response = [[[TTURLJSONResponse alloc] init] autorelease];
request.response = response;
[request send];
- (void)requestDidFinishLoad:(TTURLRequest*)request {
TTURLJSONResponse* response = request.response;
NSLog(#"%#",response);
}
Can you print all the logs in requestDidFinishLoad:?
The response is the rootObject of TTURLJSONResponse.
- (void)requestDidFinishLoad:(TTURLRequest*)request {
TTURLJSONResponse *response = request.response;
NSDictionary *dict = response.rootObject;
NSLog(#"dict : %#",dict);
}
In your case,
- (void)requestDidFinishLoad:(TTURLRequest*)request {
TTURLJSONResponse* response = request.response;
NSLog(#"%#",response);
}
The response may look like <TTURLJSONResponse: 0x125398c0>
If still nothing returns, you may check the requestDidFinishLoad: is been called and not the cache issue.
Related
Hello i'm trying to use mutiple json objects as shown in example below.
[
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
}
]
[
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
}
]
This is how it's created from the iOS side because i only create one of the objects at a time because it's for a report logging system and only need a message to be passed when it's needed. So the Json objects are created at separate times and appended to a file.
I know a valid Json string would look like this below.
[
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
},
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
}
]
However that's not what i need. Is there a way of using the two separate Json Objects?
iOS
NSString *DataString = [NSString stringWithFormat:#"{ \"DateandTime\":\"%#\", \"Description\":\"%#\", \"LoggingLevel\":\"%#\" }", #"1025", logString, [self getLogTypeName:(LOGS)level]];
NSMutableArray *CurrentData = [NSJSONSerialization JSONObjectWithData:[DataString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
NSMutableArray *ArrayOfData = [[NSMutableArray alloc] init];
[ArrayOfData addObject:CurrentData];
NSData *JsonObject = [NSJSONSerialization dataWithJSONObject:ArrayOfData options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:JsonObject encoding:NSUTF8StringEncoding];
post = [NSString stringWithFormat:#"Message=%#", jsonString];
PHP
$file = 'testingFile.txt';
// Open the file to get existing content
$current = file_get_contents($file);
if (isset($_POST['Message'])) {
// Append a new person to the file
$current .= $_POST['Message'] . PHP_EOL;
// Write the contents back to the file
file_put_contents($file, $current);
} else {
$Contents = file_get_contents($file);
echo $Contents;
}
Javascript
function GetLoggingData() {
$.get("../ISOSEC/logging/TestPHP.php", function(data){
$.each($.parseJSON(data), function(idx, obj) {
console.log(obj.DateandTime);
console.log(obj.LoggingLevel);
console.log(obj.Description);
AddLog(obj.DateandTime, obj.LoggingLevel, obj.Description);
});
});
}
Could anyone show me how i could merge the objects together if there is already a json object in the file or is there any other work around?
Thanks.
As I mentioned in my comment, you would be better off generating a file with valid JSON rather than trying to parse your own JSON syntax.
You can do this by parsing the existing JSON and appending the objects as needed.
Conceptual (not tested) example:
NSMutableArray *currentData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers errors:&errors];
[currentData addObject:newObject];
NSData *updatedJSONData = [NSJSONSerialization dataWithJSONObject:currentData options:0 errors:&errors];
Update
Okay, so as far as I see your question, you have two environments. You have the client and the server. What I didn't catch is that the individual log messages are handled by your PHP script.
Here's what I would do in your app:
NSError *error;
// Simplify the generation of your dictionary
NSDictionary *logLine = #{
#"DateandTime": #"1024"
#"Description": logString,
#"LoggingLevel": [self getLogTypeName:(LOGS)level]
};
// Create JSON string from dictionary
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:logLine options:0 error:&error];
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// Now post jsonStr as the HTTP body to your PHP script
And this is what I would do in your script:
<?php
$logFileName = 'testingFile.txt';
// Read your current log file contents
$currentLogJSON = file_get_contents($logFileName);
// Check the log for any contents
if (empty($currentLogJSON)) {
$currentLog = [];
} else {
$currentLog = json_decode($currentLogJSON);
// Ensure that the contents of the log file is an array
if (is_array($currentLog)) {
$currentLog = [];
}
}
// Get the new log line from HTTP body
$newLogLineJSON = file_get_contents('php://input');
// Decode the log line which is passed as JSON string
$newLogLine = json_decode($newLogLine);
if (json_last_error() == JSON_ERROR_NONE) {
// Append the log line to the current log
$currentLog[] = $newLogLine;
// Write the updated log contents to log file
file_put_contents($logFileName, json_encode($currentLog));
}
If your file will always look like the first example you could very well only make a preg_replace
This is only a subjestion it is probably a bad way of doing it but I think it could work.
Edit
Try this instead
$NewSingleJsonString = preg_replace("/.\].\[.\s+/s",',',$MultipleJsonString);
i have recently wanted to use Afnetworking in my ios application. the same page responds me by using ASIHTTPREQUEST. but it simply does not with the AFNetworking. Here is my effort.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"user[height]": #"10",
#"user[weight]": #"255"};
[manager POST:#"http://localhost:8888/TestingPost/post.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Now i have tried many options like adding serialization to different xml / json / html. but of no use.
On PHP page i am not doing something fancy just printing out whatever is posted on the page. still here it is.
<?php
// Show all information, defaults to INFO_ALL
header('Content-type: application/JSON');
print_r($_POST[]);
/*
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$password = $_POST['password'];
*/
//echo( "hurray");
?>
Can you please shed some light on it. i want to switch from ASIhttprequest to newest and more supported.
Here is the result for the request
Networking_example[1777:41979] Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo=0x7f9feae16d60 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7f9fedb029a0> { URL: http://localhost:8888/TestingPost/post.php } { status code: 500, headers {
Connection = close;
"Content-Length" = 0;
"Content-Type" = "text/html";
Date = "Thu, 16 Oct 2014 18:08:08 GMT";
Server = Apache;
"X-Powered-By" = "PHP/5.5.10";
} }, NSErrorFailingURLKey=http://localhost:8888/TestingPost/post.php, com.alamofire.serialization.response.error.data=<>, NSLocalizedDescription=Request failed: internal server error (500)}
If your PHP is using $_POST, that means that you are ok using the default requestSerializer of AFHTTPRequestSerializer (i.e. an application/x-www-form-urlencoded request).
But your JSON is not generation JSON response, so you have to change the responseSerializer to AFHTTPResponseSerializer.
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
And your PHP page is reporting a 500 error. That is an "Internal Server Error", for which the status code definition says:
The server encountered an unexpected condition which prevented it from fulfilling the request.
That suggests a PHP error. Perhaps you intended:
print_r($_POST);
Generally, when interacting with web service, it's better to generate JSON response, e.g.
echo(json_encode($_POST));
Obviously, if you generate JSON response, you might also want to use the default [AFJSONResponseSerializer serializer] setting, rather than changing it to AFHTTPResponseSerializer.
I'm trying to visit the php page from my server, but no return. The code below should be fine, because when I change my site address (site1111111) to another one (site222222), the code works. The site2 uses JSON.aspx, which I don't know the code, but returns:
{aaaa:false}
Edit and Add: Not sure if it matters, when I say site1111111, it's actually site222222/subfolder/. End edit.
My PHP code is simple test, just populate the same json string:
<html><body>
$arr = array ('aaaa'=>false);
echo json_encode($arr);
</body></html>
The iOS app code is here:
NSString *urlString = #"http://site111111111111111111/welcome.php";
//urlString = #"http://site222222222222/JSON.aspx?function=ffff&item=aaaa";
NSURL *url = [NSURL URLWithString:urlString];
NSError *error;
NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
NSLog(#"%#", data);
//<7b226973 64696769 74616c22 3a66616c 73657d> //print data from site2222222
//<3c68746d 6c3e0d0a 3c626f64 793e0d0a 0d0a3c21 2d2d5765 6c636f6d 65203c62 723e0d0a 596f7572 20656d61 696c2061 64647265 73732069 733a200d 0a2d2d3e 0d0a0d0a 7b226973 64696769 74616c22 3a66616c 73657d0d 0a3c2f62 6f64793e 0d0a3c2f 68746d6c 3e0d0a> //data from site11111
if (error)
{
NSLog(#"error==%#==",[error localizedDescription]);
}
else
{
NSLog(#"no error for request"); //both site1111 and site2222 print this out
NSError *errorInJsonParsing;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorInJsonParsing];
if(errorInJsonParsing)
{
NSLog(#"error in json==%#==",[error localizedDescription]);
}
else
{
if ([[json valueForKey:#"aaaa"] boolValue] ) {
NSLog(#"YES");
} else {
NSLog(#"NO");
}
}
}
When running the code, I got null json, printed from if condition if(errorInJsonParsing).
I don't know if I miss anything that connects my php and ios request. Please help. TIA!
site1111 is not returning json, it's returning html. if you decode those hex bytes you'll see this:
<html>
<body>
<!--Welcome <br>
Your email address is:
-->
{"isdigital":false}
</body>
</html>
Fix the site so it returns json and you should be good to go.
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.