i need to get values from mysql and display in Xcode textfield dynamically.( want to automatically enter the string in lastName and phoneNumber when user enters the firstName)
here my Xcode..
NSError *err;
NSString *strURL=[NSString stringWithFormat:#"http://192.168.1.22:81/priya/sam.php"];
NSData *dataURL=[NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *name=firstname.text;
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:dataURL options: NSJSONReadingMutableContainers error:&err];
NSArray *array=[jsonArray objectForKey:#"key"];
lastname.text=[[array objectAtIndex:0]objectForKey:#"lastname"];
phone.text=[[array objectAtIndex:0]objectForKey:#"phone"];
then how to find text array of index using first-name.
thanks in advance
I'm not quite sure what the problem is (do you have only 1 row instead of desired number of rows?)
Shows all rows from received data:
for (NSDictionary *item in array) {
firstname.text=[item objectForKey:#"firstName"];
lastname.text=[item objectForKey:#"lastname"];
phone.text=[item objectForKey:#"phone"];
}
The output you got for server is a dictionary and the parent key is "Key". To get array index dynamically please see the code below
NSMutableArray *infoArray=[[NSMutableArray alloc]init];
infoArray =[jsonArray objectForKey:#"Key"]; // this is your array with all information stored index wise.
NSLog(#"%#", infoArray);
for(int i=0; i<infoArray.count; i++)
{
NSLog(#"%#", [[infoArray objectAtIndex:i]objectForKey:#"firstname"]);
NSLog(#"%#", [[infoArray objectAtIndex:i]objectForKey:#"lastnamename"]);
}
or
The issue is with PHP side ask them to replace "[" and "]" with "(" and ")".
Hope this will help
Related
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!
I have This PHP Code With Arrays And Loops, Trying to convert it into Objective-c "iOS"
foreach($arr as $item)
{
$data[$item[date]][]=$var;
}
What i did so far is :
for(id theKey in result)
{
leEvent[[NSString stringWithFormat:#"%#",[theKey objectForKey:#"event_date"]]]=#"asd";
}
but it still overlaps each other if same key.
So any Idea ? Thanks in advance.
UPDATE :
I have this JSON:
[{"id":"1","title":"test","event_date":"2014-01-28","description":"this
is a test desc ","time_stamp":"2014-01-28
13:04:12"},{"id":"2","title":"test2","event_date":"2014-01-29","description":"this
is a test desc2 ","time_stamp":"2014-01-28
13:21:36"},{"id":"3","title":"test3","event_date":"2014-01-29","description":"this
is a test desc3","time_stamp":"2014-01-28 13:21:36"}]
I want To make out of it Array That They key of Array is the Date : and inside each date other information
Expmple $data['2014-01-29'] should have 2 arrays in side it but i want to do it in iOS
We have "for in" loop in objective C
For example:
for( NSNumber *num in numArray)
{
//Write your code here
}
Let me know if this is not what you want or you need some more info
Update:
You don't need a ForLoop in here.
Let's say result is your NSDictionary object.
So,
[result objectForKey:#"event_date"]
will give object for key "event_date".
By your code.. It seems like you are trying to set value for the key "event_date".
So your code would be something like this,
[result setObject:#"asd" forKey:#"event_date"];
Let me know if it does not help.
I would suggest you to use JSONSerialization. This might ease up your task.
NSError* err = nil;
NSString* myJSONFile = [[NSBundle mainBundle] pathForResource:#"myFileName" ofType:#"json"];
NSArray* dataTypes = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:myJSONFile] options:kNilOptions error:&err];
NSLog(#"Imported data Types: %#", dataTypes);
//This will print the data you just imported..
NSMutableArray *myArray= [[NSMutableArray alloc]init];
[dataTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
if([obj objectForKey:#"event_date"] isEqualTo:#"myDate")
{
[myArray addObject:obj];
}
}];
I've checked this code... Working fine.. Let me know if any issues are there
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.
Well, I decided that it's time to learn a new skill, programming objective-c. My programming knowledge is very minimal, It consists of PHP, little bit of HTML, and a little bit of MySQL. What I want to do is take some JSON that is made with php and populate a iOS table view.
here is my json.php:
<?php
$array = array(1,2,3,4,5,6,7,8,9,10);
$json = json_encode($array);
echo $json;
?>
My only problem is, is I have no idea where to start on how to use JSONKit framework. https://github.com/johnezang/JSONKit/ I would prefer to use JSONKit over the other alternatives just because it seems it has more support.
NSString *strURL = [NSString stringWithFormat:#"http://api.tekop.net/json.php"];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);
I was able to print the results of the JSON page in the debug console. Now my only question is what next? I have tried to look for some tutorials online but all I could find was something more advanced Jason phraser. To advanced for my basic needs. I know my questions very vague and open to a lot of different answer, but I figured this is the place to ask these types of questions.
iOS has its own JSON parse now called NSJSONSerialization.
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
You can have a look. I always use it like this.
[NSJSONSerialization JSONObjectWithData:tmpData
options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
error:nil]
sample by modifying your code:
NSString *strURL = [NSString stringWithFormat:#"http://api.tekop.net/json.php"];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSArray *arrayResult = [NSJSONSerialization JSONObjectWithData:dataURL
options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
error:nil];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
Something to note is that, if your json is an array based, use NSArray to store the result. If your json is an hash based, use NSDictionary. (Hope I say it clearly, I dont know the related terms to describe)
What have you tried?
NSArray *array = [dataURL objectFromJSONData];
NSAssert([array isKindOfClass:[NSArray class]], #"This should be an array.");
for (NSNumber *value in array) {
NSAssert([value isKindOfClass:[NSNumber class]], #"This should be a number.");
NSLog(#"%#", value);
}
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]}