unable to retrieve json data in objective-c - php

I'm trying to retrieve json data from mysql database in iphone. This is my .php file.
I would like to retrieve this data so that I have some code in my .m
- (void)jsonParse{
NSString* path = #"http://phdprototype.tk/getResultData.php";
NSURL* url = [NSURL URLWithString:path];
NSString* jsonString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary* resultDic = [dic objectForKey:#"maxid"];
NSString* recData = [resultDic objectForKey:#"recommendData"];
NSString* rData = [resultDic objectForKey:#"room"];
NSString* lData = [resultDic objectForKey:#"level"];
NSLog(#"recommendData = %#, room = %#, level = %#",recData,rData,lData);}
What I expect is to get data from recommendData, room, and level, but the debugger windows shows it did not get anything. This is what the debugger shows
2014-03-12 15:13:21.500 Semantic Museum[24289:907] recommendData = (null), room = (null), level = (null)
do I miss something??

Looks a problem with the server response headers.
I am seeing the Content-Type come back as
text/html
but it should be something like
application/json

This issue is coming because it's static text(try to View Source in your browser, it's returning extra parameter with JSON). If it's JSON, you need to check that from PHP the header value is set properly.

Related

Passing Date from xCode to PHP with NSData

I am trying to pass a date from Xcode to a PHP page (stores the Date to a mysql DB) however NSData doesn't seem to like the format of the Date.
//Format date for mysql & PHP
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *strToday = [dateFormatter stringFromDate:[NSDate date]];
NSString *strURL = [NSString stringWithFormat:#"http://www.TESTSERVER.com/Items.php?uID=123456789&item1=30&item2=5&startDate=%#&endDate=%#", strToday, strToday];
//strURL=[strURL stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSLog(#"%#", strURL);
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);
I have tested the PHP page by entering data manually and it works without any issues. However when I ran the code above it doesn't work, I've isolated the issue to the date and I believe that NSData has a problem with the space in my Date Format (between the Date and Time).
I tried filling the gap with %20 (URL encoding etc.) and the connection is made to the db but the date field is not in the right format so it appears as null in the mysql database.
I'd rather not start parsing strings in my PHP, does anyone know how to fix this?
Below is my PHP code: -
<?PHP
$hostname = "XXX";
$username = "XXX";
$password = "XXX";
$database = "XXX";
$db_handle = mysql_connect($hostname, $username, $password);
$db_found = mysql_select_db($database, $db_handle);
$uID = $_GET['uID'];
$item1 =$_GET['item1'];
$item2 =$_GET['item2'];
$startDate =$_GET['startDate'];
$endDate =$_GET['endDate'];
if ($db_found) {
$sql = "INSERT INTO Items (uID, item1, item2, startDate, endDate) VALUES ('$uID','$item1','$item2','$startDate','$endDate');";
//$cleanSQL = str_replace("%20"," ",$sql);
$result = mysql_query($sql);
mysql_close($db_handle);
print "Records added to the database";
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
There's a many problems with this code, but it's impossible to diagnose what precisely is causing the problem you describe on the basis of the limited information provided. A few observations:
You definitely need to percent escape the date string. The space is not acceptable in a URL (nor the body of a standard x-www-form-urlencoded request).
If you are inserting data, you should be issuing POST request, not adding this stuff to a URL, in effect issuing GET request.
You should not be issuing request with dataWithContentsOfURL. Not only is that GET, but it's synchronous and doesn't report the error.
If you still have problems, you should observe this request with Charles or similar tool. Observe the same request that you have working via web browser and compare and contrast.
Personally, when I have problems, I temporarily change my PHP code to return the data I passed to it, so I can make sure that everything was received correctly. It's a simple, but effective, way to confirm that everything was received properly.
If you are passing date strings to the server, you generally should use GMT timezone, to avoid problems stemming from the server not knowing what time zone the user's device is located. Likewise, you should use en_US_POSIX locale, to avoid problems with non-gregorian calendars. See Apple Technical Q&A 1480.
Pulling that all together, you end up with something more like:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; // if you REALLY want to use local timezone, eliminate this line, but I'd really advise sticking with GMT when using formatters to create and parse date strings that you're sending to a remote server
NSString *strToday = [dateFormatter stringFromDate:[NSDate date]];
NSURL *url = [NSURL URLWithString:#"http://www.TESTSERVER.com/Items.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *body = [[NSString stringWithFormat:#"uID=123456789&item1=30&item2=5&startDate=%#&endDate=%#", strToday, strToday] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"]; // not necessary, but good practice
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// use the data/error/response objects here
if (data) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"responseString = %#", responseString);
} else {
NSLog(#"error = %#", error);
NSLog(#"response = %#", response);
}
}];
[task resume];
// don't try to use the string here, because the above happens asynchronously
Frankly, I don't like this overly simplistic mechanism of setting the body (if any of the fields included special characters like + or &, the above wouldn't work). But if the parameters are precisely as you've outlined them in your question, this simplistic solution should work. But, if you want something a little more robust in this regard, see the encodePostParameters method shown in https://stackoverflow.com/a/22887238/1271826.
By the way, I'd suggest considering using AFNetworking, as that gets you out of the weeds of manually constructing requests.
But, going back to your original question, we cannot advise you further without seeing the server code or you doing more debugging (Charles, confirming that the values are correctly being received, etc.).

UITextView prints JSON identifier instead of desired parsed data

Like the title says, my UITextView is setup to print data found within "userName". Instead of behaving appropriately, it prints "userName".
PHP code:
<?php
header('Content-Type: application/json');
$arr = array ('userName'=>'derekshull', 'userBio'=>'This is derekshulls bio','userSubmitted'=>'15');
echo json_encode($arr);
?>
Objective C:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *myURL = [[NSURL alloc]initWithString:#"http://techinworship.com/json.php"];
NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];
if(!error)
{
for (id element in jsonArray) {
textview.text = [NSString stringWithFormat:#"%#", [element description]];
// text view will contain last element from the loop
}
}
else{
textview.text = [NSString stringWithFormat:#"Error--%#",[error description]];
}
}
What am I missing here? Also, when run, the application does not crash and give error. However, the following is documented in the DeBug Area.
2014-03-24 20:20:53.258 testtest[11434:60b] Unknown class textview in Interface Builder file.
I don't currently have a OSX computer available so I can't evaluate my code.
It seems like the array you have in you PHP code is an associative array and the JSON will be similar. When you are parsing the JSON string in your Obj-C code try assigning it to a NSDictionary, this way you will have access to the associative array.
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];
When using the data in the jsonArray don't iterate it, use the NSDictionary method objectForKey to get get the value you want.
As an example, to get the value of userName, you can do this:
[jsonArray objectForKey: #"userName"] // jsonArray is not actually a array, but a dictionary now
And to change the text of the textview, you can do the following:
textview.text = [NSString stringWithFormat:#"%#", [jsonArray objectForKey: #"userName"]];
Ask if something is unclear!
Cheers!

http request loop not sending

Why does this not send a http request? i'm trying to add all friends from the person logged in into the mysql table. When i use this url manually in my browser http://www.ratemyplays.com/api/post_friends.php?name=%#&id=%#&userid=%#
it add the values %#, but not when i run the objective-c code. What am i doing wrong with the http request loop?
for (NSDictionary<FBGraphUser>* friend in friends) {
NSString *strURL = [NSString stringWithFormat:#"http://www.ratemyplays.com/api/post_friends.php?name=%#&id=%#&userid=%#",friend.name, friend.id, currentId];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);
}
I think you need to be more clear what are you trying to accomplish here.. the Url that nslog prints out looks fine.. what do you mean by adding %#? all you did in this look is creating again and again -one- string of URL and didn't do anything with it...

iOS trying to post location updates to a server

Within my application, I am trying to post the gps coordinates of a users position to a server for storage so that I can eventually design a map that displays all the users locations. I am using HTTP get and a custom PHP API to handle the data passing from app to db. The problem I have is, every time didUpdateLocations is called, I update the server. It works sometimes, but then sometimes my query string says there is an undefined variable and blank data is being posted int he db. Why is sometimes it undefined, and sometimes not? Also, is there a better way to handle the data passing? I was going to use ASIHTTPRequest but I am using ARC and so that is no help to me.
Code:
- (void)postLocationUpdateFor:(NSString *)deviceToken withDeviceID:(NSString*)deviceID withLatitude:(NSString *)latitude andLongitude:(NSString *)longitude {
NSString *apiURL = [NSString stringWithFormat:ServerApiURL2, deviceToken, deviceID, latitude, longitude];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:apiURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *currentLocation = [locations lastObject];
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] stringForKey:#"deviceToken"];
NSString *latitude = [NSString localizedStringWithFormat:#"%f",currentLocation.coordinate.latitude];
NSString *longitude = [NSString localizedStringWithFormat:#"%f",currentLocation.coordinate.longitude];
NSLog(#"Entered new Location with the coordinates Latitude: %# Longitude: %#", latitude, longitude);
[self postLocationUpdateFor:#"123" withDeviceID:deviceToken withLatitude:latitude andLongitude:longitude];
}
didUpdateLocations
can be called when you actually lost your location: entered into an Elevator / building. That's why is sometimes empty.
I would check and validate that location values before I will send the server.

Iphone JSON-Framework EOF Error

I'm attempting to use Json-Framework to parse output (on the iPhone) from my website. The data on the website is an array of news objects... passed through PHP's json_encode().
The JSON Output is here: http://pastebin.com/Be429nHx
I am able to connect to the server and store the JSON data, then I do:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// Create a dictionary from the JSON string
NSDictionary *results = [jsonString JSONValue];
NSArray *items = [results valueForKeyPath:#"data.array"];
NSLog(#" NewsID : %#", [[items objectAtIndex:1] objectForKey:#"newsID"]);
and I receive the following error from the NSLog() line:
-JSONValue failed. Error is: Didn't find full object before EOF
Event Id : (null)
STATE: <SBJsonStreamParserStateStart: 0x4e3c960>
JSONValue failed. Error is: Token 'key-value separator' not expected before outer-most array or object
Event Id : (null)
Any help will be greatly appreciated... thanks!!!
It might be because your JSON is structured as an array, so you should just do:
NSArray *items = [jsonString JSONValue];
NSLog(#" NewsID : %#", [[items objectAtIndex:1] objectForKey:#"newsID"]);
or, alternately, change the JSON itself so that it's more like:
{"somekeyname":[your existing json array]}

Categories