I have a button that shows some part of the URL on a text view, but I would like for this information to be shown in a specific format.
- (IBAction)Accesos:(id)sender {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"URL"]];
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray* Response_array = [json objectForKey:#"avenidas"];
for (int i=0; i < Response_array.count; i++){
NSDictionary* item = [Response_array objectAtIndex:i];
NSString* name = [item objectForKey:#"name"];
NSString* state = [item objectForKey:#"state"];
NSString* space = #"\n";
NSString* formattedString = [NSString stringWithFormat:#"%#%#: %#",space, name, state];
txt_webservice_response.text = formattedString; }
}
The information is shown the same as in the URL I would like to display the information like name: state and then the state to be in color depending the type if it is possible.
NSArray* items = [someDictionary objectForKey:#"avenidas"];
NSDictionary* item = [items objectAtIndex:someIndex];
NSString* name = [item objectForKey:#"name"];
NSString* state = [item objectForKey:#"state"];
NSString* formattedString = [NSString stringWithFormat:#"%#:%#", name, state];
(All of this is first-week stuff -- if you don't know it you need to spend more time studying the fundamentals.)
You can create the HTML for the response and show it to webView for coloring
Related
Below is my code to access the JSON API from Edmunds.com, this works perfectly to access the information I am just having trouble with accessing the key, value pairs.
NSURL *equipmentURL = [NSURL URLWithString: [NSString stringWithFormat:#"https://api.edmunds.com/api/vehicle/v2/styles/%#/equipment?fmt=json&api_key=%#", self.carID, apiKey]];
NSData *jsonData = [NSData dataWithContentsOfURL:equipmentURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.engineArray = [NSMutableArray array];
NSArray *equipmentArray = [dataDictionary objectForKey:#"equipment"];
for (NSDictionary *carInfoDictionary in equipmentArray) {
NSArray *attributes = [carInfoDictionary objectForKey:#"attributes"];
NSLog(#"%#", attributes);
}
In the NSLog from the above code shows this:
2016-11-03 10:21:26.029 CarWise[25766:1896339] (
{
name = "Engine Immobilizer";
value = "engine immobilizer";
},
{
name = "Power Door Locks";
value = "hands-free entry";
},
{
name = "Anti Theft Alarm System";
value = "remote anti-theft alarm system";
}
)
My main question is how can I access the name and value for each array? Let's say I want to create a UILabel that will have the string of one of the values?
Probably this will help
// Array as per the post
NSArray *attributes = (NSArray *)[carInfoDictionary objectForKey:#"attributes"];
// Loop to iterate over the array of objects(Dictionary)
for (int i = 0; i < attributes.count; i++) {
NSDictionary * dataObject = [NSDictionary dictionaryWithDictionary:(NSDictionary *)attributes[i]];
// This is the value for key "Name"
NSString *nameData = [NSString stringWithString:[dataObject valueForKey:#"name"]];
NSLog(#"Value of key : (name) : %#", nameData);
}
I am using this method to show the string of location using current location latitude and longitude but it is showing differently
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",location.coordinate.latitude, location.coordinate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSData *data = [locationString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *dic = [[json objectForKey:#"results"] objectAtIndex:0];
NSArray* arr = [dic objectForKey:#"address_components"];
//Iterate each result of address components - find locality and country
NSString *cityName;
NSString *countryName;
for (NSDictionary* d in arr)
{
NSArray* typesArr = [d objectForKey:#"types"];
NSString* firstType = [typesArr objectAtIndex:0];
if([firstType isEqualToString:#"locality"])
cityName = [d objectForKey:#"long_name"];
if([firstType isEqualToString:#"country"])
countryName = [d objectForKey:#"long_name"];
}
NSString* locationFinal = [NSString stringWithFormat:#"%#,%#",cityName,countryName];
NSLog(#"Final Location %# ",locationFinal);
but final location is showing this type :-
Final Location नठदिलà¥à¤²à¥,India
Why it is showing this type? Can anyone know about this.
Please supply the language with the API params. If language is not supplied, the geocoder attempts to use the preferred language as specified in the Accept-Language header, or the native language of the domain from which the request is sent.
So please replace the code as with the language parameter as like this.
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false&language=en",location.coordinate.latitude, location.coordinate.longitude];
and try again.
I believe that is an uninitialzed variable which is pointing into random memory.
Try:
NSString *cityName = nil;
NSString *countryName = nil;
Short-circuit your for loop:
for (NSDictionary* d in arr)
{
// Add this after the existing code:
if (cityName && countryName)
break;
}
and check for errors before presenting the results:
if (cityName && countryName) {
NSString* locationFinal = [NSString stringWithFormat:#"%#,%#",cityName,countryName];
NSLog(#"Final Location %# ",locationFinal);
} else {
NSLog(#"Failed to find location");
}
Finally your JSON-processing code does no error-checking at all. That's a mistake.
I want to set some text which is coming in web-response to a label. Here is my response from web-service.
{
success = 1;
"user_post" = (
{
"associated_since" = "02 December 2015";
"company_name" = "Amartam";
"user_email" = "xxxx";
"user_name" = "xxxxxxx";
"user_phoneno" = 000000;
}
);
I am trying to set the value of user_name in a label, but got only ( in the label. Here is the code which I have tried.
NSDictionary* response=(NSDictionary*)[NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSDictionary *userPost =[response valueForKey:#"user_post"];
NSString *userName = [userPost valueForKey:#"user_name"];
self.customerNameLabel.text = [NSString stringWithFormat:#"%#",userName];
NSString *userName = [[[response objectForKey:#"user_post"] objectAtIndex:0] valueForKey:#"user_name"];
your user_post is array containing dictionary.
so you need to get the array and get the desired dictionary from those array.
NSDictionary* response=(NSDictionary*)[NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *userArray = [response valueForKey:#"user_post"];
NSDictionary *userPost =[userArray firstObject];
NSString *userName = [userPost valueForKey:#"user_name"];
self.customerNameLabel.text = [NSString stringWithFormat:#"%#",userName];
I've a NSMutableArray array having NSDictionary keys as:
NSMutableArray *arr=#[#{#"A":#{#"user":#"obj1",#"friend":#"obj2"}}];
No I want to add objects to this NSMutableArray.
My Code:
for (int i = 0; i < 10; i++)
{
NSString *user = #"A"+i;
for(int i=0;i<50;i++) {
NSString *friend1 = #"B"+i;
NSString *friend2 = #"C"+i;
NSString *friend3 = #"D"+i;
}
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
NSString *y= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#",y);
Desired Output:
{"A":[{"user":"A1","friend":"B1"},{"user":"A1","friend":"B2"},{"user":"A2","friend":"B1"}]}
How can I set my objects in order to achieve desired output.
NSString* singleObjectTemplate = [NSString stringWithFormat:#"{\"user\" : \"%#\",\"friend\" : \"%#\"}", user, friend];
NSString* validJsonTemplate = [NSString stringWithFormat:#"{\"A\":[%#]}", singleObjectTemplate];
Something like this. You can modify it as per your requirement to add multiple entries.
I hope this helps you in some way. Cheers!! :)
EDIT:
Suppose you want to add 3 objects to it.
NSString *str = #"";
for (int i = 0; i<3; i++)
{
NSString* singleObjectTemplate = [NSString stringWithFormat:#"{\"user\" : \"%#\",\"friend\" : \"%#\"}", user, friend];
str = [str stringByAppendingString:singleObjectTemplate];
if(i<2)
str = [str stringByAppendingString:#", "];
}
NSString* validJsonTemplate = [NSString stringWithFormat:#"{\"A\":[%#]}", str];
I am trying to parse the file location from the following so that image can be displayed. How do I do it?
[
{
"title":"testing barcode display",
"body":"lets see if it renders \r\n\r\n",
"author":"1",
"created":"1373490143",
"nid":"5",
"Barcode":"<img class=\"barcode\" typeof=\"foaf:Image\" src=\"http://mysite.com/sites/default/files/barcodes/95b2d526b0a8f3860e7309ba59b7ca11QRCODE.png\" alt=\"blahimage\" title=\"blahimage\" />"
}
]
I have a table view which displays the title tag. I need to display the entire content in the detail view. I can do everything except the Barcode tag. Please advise.
If it should be done, parse the xml
NSString *xmlString = #"<img class=\"barcode\" typeof=\"foaf:Image\" src=\"http://mysite.com/sites/default/files/barcodes/95b2d526b0a8f3860e7309ba59b7ca11QRCODE.png\" alt=\"blahimage\" title=\"blahimage\" />";
GDataXMLElement *xmlElement = [[GDataXMLElement alloc]initWithXMLString:xmlString error:nil];
NSArray *attributes = [xmlElement attributes];
[attributes enumerateObjectsUsingBlock:^(GDataXMLNode * node, NSUInteger idx, BOOL *stop) {
NSLog(#"%# : %#",node.name,node.stringValue);
}];
OR
NSString *class = [[xmlElement attributeForName:#"class"] stringValue];
NSString *typeOf = [[xmlElement attributeForName:#"typeof"] stringValue];
NSString *src = [[xmlElement attributeForName:#"src"] stringValue];
NSString *alt = [[xmlElement attributeForName:#"alt"] stringValue];
NSString *title = [[xmlElement attributeForName:#"title"] stringValue];
Use json-framework or something similar.
If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];
// now you can grab data out of the dictionary using objectForKey or another dictionary method
You have to convert json string in nsdictionary, so try this
SBJSON *json = [[SBJSON new] autorelease];
NSError *error;
NSDictionary *dict = [json objectWithString:YOUR_JSON_STRING error:&error];
add user this dictionary to display details in tableView