I am new in iOS and I am facing problem regarding to get IndexPath.row outside cellforrowAtIndexPath method i.e on didFinishLoading. My code is like this
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
loginStatus = [[NSString alloc] initWithBytes: [myNSMDataFromServer mutableBytes] length:[myNSMDataFromServer length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatus);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatus error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResult = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResult);
NSDictionary* Address=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",Address);
NSDictionary *new =[Address objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"TFMComplaints_GetNewResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"TFMComplaints_GetNewResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSLog(#"Now String is =%#",string);
NSData *data =[string dataUsingEncoding:NSUTF8StringEncoding];
NSError* error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSUTF8StringEncoding error:&error];
NSIndexPath *selectedIndexPath = [closetbl indexPathForSelectedRow];
NSDictionary *firstObj = [array objectAtIndex:selectedIndexPath.row];
idarray=[[NSMutableArray alloc]init];
idarray=[firstObj valueForKey:#"Key"];
NSLog(#"Result Array =%#",idarray);
}
I am getting only one value that is on 0.
Thanks in Advance!
Just add a for loop for array:
for (int i = 0; i < array.count; i++)
{
//where i will be the index path. You can use it like this
NSDictionary *firstObj = [array objectAtIndex:i];
}
In your case you can use it like this:
idarray=[[NSMutableArray alloc]init];
for (int i = 0; i < array.count; i++){
NSDictionary *firstObj = [array objectAtIndex:i];
[idarray addObject:[firstObj valueForKey:#"Key"]];
NSLog(#"Result Array =%#",idarray);
}
NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];
For more details follow: https://developer.apple.com/reference/uikit/uitableview/1615000-indexpathforselectedrow
Hope this helps.
You can use below code to get the indexpath and from this indexpath you can get also the selected cell.
let indexPath = self.tblObj.indexPathForSelectedRow!
let currentCell = self.tblObj.cellForRowAtIndexPath(indexPath)! as! YourTableViewCell
Related
I am trying to parse an NSString to NSArray but couldn't get any success. Here is my String: NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
I want this string mapped to NSArray.
NSArray *tempArray = points;
OK, code golf (untested):
NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSError *error = nil;
NSArray *pointsArray = [NSJSONSerialization JSONObjectWithData:[points dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
for (NSArray *point in pointsArray) {
NSAssert([point count] == 2, #"Invalid point");
// do thing with point
CGPoint pt = CGPointMake([point[0] floatValue], [point[1] floatValue]);
}
Can you plz try this, May it solve your problem,
NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSArray* arrayOfStrings = [points componentsSeparatedByString:#","];
NSLog(#"%#",arrayOfStrings);
NSMutableArray *copyArray = [arrayOfStrings mutableCopy];
NSMutableString *stringFirst = (NSMutableString *)[copyArray objectAtIndex:0];
NSMutableString *stringLast = (NSMutableString *)[copyArray lastObject];
stringFirst=[stringFirst substringFromIndex:1];
stringLast=[stringLast substringToIndex:stringLast.length-1];
[copyArray replaceObjectAtIndex:0 withObject:stringFirst];
[copyArray replaceObjectAtIndex:(copyArray.count-1) withObject:stringLast];
NSMutableArray *yourarray = [[NSMutableArray alloc] init];
for (int i=0; i<=(copyArray.count/2); i+=2) {
[yourarray addObject:[NSString stringWithFormat:#"%#,%#",[copyArray objectAtIndex:i], [copyArray objectAtIndex:i+1]]];
}
NSLog(#"%#",yourarray);
Happy Coding!!
That string looks like JSON so you can use NSJSONSerialization
NSData * data = [points dataUsingEncoding: NSUTF8StringEncoding];
NSError * error = nil;
NSArray * arrayOfPointArrays = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
This is my JSON:
-elements: [
{
HomeworkElementSession: {
id: "608743",
name: "Interval for x",
description: "",
}
}
]
...
I was able to get to the point where I have an actual NSArray representing the "elements" node and therefore containing only one object in the array.
But I have no idea how to reach this string "name".
What i did was:
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* homeworkSession = [elements objectAtIndex:i];
NSString* name = [homeworkSession objectForKey:#"name"];
NSLog(#"%#",name);
}
But i get nil in Log.
What am I doing wrong ?
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* homeworkSession = [elements objectAtIndex:i];
NSDictionary* dataDict = [homeworkSession objectForKey:#"HomeworkElementSession"];
NSString* name = [dataDict objectForKey:#"name"];
NSLog(#"%#",name);
}
You need to get the Dictionary for key HomeworkElementSession first
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* mainhomeworkSession = [elements objectAtIndex:i];
NSDictionary* homeworkSession = [mainhomeworkSession objectForKey:#"HomeworkElementSession"];
NSString* name = [homeworkSession objectForKey:#"name"];
NSLog(#"%#",name);
}
Hope it helps you..!
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(NSDictionary *dict in elements){
NSDictionary* dataDict = [dict objectForKey:#"HomeworkElementSession"];
NSString* name = [dataDict objectForKey:#"name"];
NSLog(#"%#",name);
}
Try this may be help full ,
Note: you are getting output in NSString so use this
NSString *singleHomework = #"your data";
NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:[singleHomework dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:Nil];
NSMutableArray *dataArray = [dataDic valueForKey:#"elements"];
NSLog(#"Name Print %#",[dataArray[0] valueForKey:#"name"]);
First, I'm not sure why you have a hyphen in the dictionary key "-elements". That could be a problem. However, your main problem is that your JSON is an array containing a single dictionary which then contains a dictionary (HomeworkElementSession) which has attributes.
NSString * json = #"{\"elements\": [{\"HomeworkElementSession\": {\"id\": \"608743\", \"name\":\"Interval for x\", \"description\": \"\"}}]}";
NSData * jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&e];
NSLog(#"dict=%#", dict);
I have an array that loaded with data from other method. The data type is like that in the debug for KEYS as in the code.
<__NSArrayI 0x9e82fc0>(
{
"choice_name" = "Data0";
},
{
"choice_name" = "Data1";
},
{
"choice_name" = "Data2";
},
Then I have called it twice in different method as I commented below and I get the value of the arrray: array0 or array1 nil. Where would be my problem?
- (void)requestPosistion:(ASIFormDataRequest *)request{
NSData *responseData = [request responseData];
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *result = [jsonString JSONValue];
[jsonString release];
if (![SettingVO isValidResponce:result]) return;
CXMLDocument *doc = [[[CXMLDocument alloc] initWithXMLString:[result objectForKey:#"Response"] options:0 error:nil] autorelease];
NSArray *nodes = [doc nodesForXPath:#"/root" error:nil];
NSLog(#"choiceList is %#", nodes);
if([[[[nodes objectAtIndex:0] attributeForName:#"success"] stringValue] isEqualToString:#"true"])
{
NSArray *nodes3 = NULL;
nodes3 = [doc nodesForXPath:#"/root/cl_choicelist/cl_choice" error:nil];
NSLog(#"node3%#", nodes3);
res = [[NSMutableArray alloc] init];
for (CXMLElement *node in nodes3) {
item = [[NSMutableDictionary alloc] init];
int counter;
for(counter = 0; counter < [node childCount]; counter++) {
[item setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] name]];
}
[item setObject:[[node attributeForName:#"choice_name"] stringValue] forKey:#"choice_name"];
NSLog(#"item %#", item);
[res addObject:item];
[item release];
}
NSLog(#"res %#", res);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjects:res forKeys:res];
//NSArray *keys = [plistDict allKeys];
//NSArray *array0 = [[NSArray alloc] initWithArray:[plistDict valueForKey:#"choice_name"]]; //array0 = nil.
NSArray *array1 = [plistDict objectForKey:#"choice_name"]; //array1 = nil.
Working code looks like that:
[[res objectAtIndex:0] objectForKey:#"choice_name"] //returns Data0
[[res objectAtIndex:1] objectForKey:#"choice_name"] //returns Data1
Most probably you want to use "indexPath" at objectAtIndex:
[[res objectAtIndex:[indexPath row]] objectForKey:#"choice_name"]
<__NSArrayI 0x9e82fc0>( { "choice_name" = "Data0"; }, { "choice_name" = "Data1"; }, { "choice_name" = "Data2"; },
This is an array. Inside the array you have object of NSDictionary with key "choice_name".
So in order to retrieve you need to iterate through the array to get all the kvp.
Replace your line with:
NSString *str = [plistDict valueForKey:#"choice_name"];
You have string for that key nor array.
Is always good to make sure your plistDict is not nil.
In NSDictionary you can have onelly one pair with key #choice_name. Even if you "put" more then one in NSDictionary, all other will just override previous value.
so valueForKey can return onelly one object and not the whole array, because there is onelly one key #choice_name.
Please help me debug this code
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"http://cnapi.iconnectgroup.com/api/UserProfile?id=1"]];
NSString *json = [NSString stringWithContentsOfURL:urls encoding:NSASCIIStringEncoding error:&error];
NSLog(#"JSon data = %# and Error = %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(#"JSON data is :: %#", myJsonArray);
for(NSDictionary *jsonDictionary in myJsonArray)
{
//NSString *uids = jsonDictionary[#"UID"];
NSString *address1 = jsonDictionary[#"Address1"];
NSString *address2 = jsonDictionary[#"Address2"];
NSString *city = jsonDictionary[#"City"];
NSString *emailId = jsonDictionary[#"EmailID"];
NSString *fname = jsonDictionary[#"FName"];
NSString *fax = jsonDictionary[#"Fax"];
NSString *lname = jsonDictionary[#"LName"];
NSString *password = jsonDictionary[#"Password"];
NSString *phone = jsonDictionary[#"Phone"];
NSString *state = jsonDictionary[#"State"];
NSString *uids = [jsonDictionary objectForKey:#"UID"];
NSString *zip = jsonDictionary[#"Zip"];
NSString *company = jsonDictionary[#"company"];
NSString *department = jsonDictionary[#"department"];
NSLog(#"Uid is = %#", uids);
NSLog(#"First Name = %#", fname );
NSLog(#"Last Name = %#", lname);
NSLog(#"Company = %#", company);
NSLog(#"Email Id = %#", emailId);
NSLog(#"Password = %#", password);
NSLog(#"Department = %#", department);
NSLog(#"Address 1 = %#", address1);
NSLog(#"Address 2 = %#", address2);
NSLog(#"City = %#", city);
NSLog(#"State = %#", state);
NSLog(#"Zip = %#", zip);
NSLog(#"Phone = %#", phone);
NSLog(#"Fax = %#", fax);
}
}
});
[activity stopAnimating];
self.activity.hidden = YES;
}
Image will give you where the error is. I get this error after clicking stepover to debug. I also tried
NSString *address1 = [jsonDictionary objectForKey:#"Address1"];
From the output of url, it shows it's not array but a dictionary. You are trying to convert to array here.
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
instead use this
NSDictionary *myJsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
then remove that for loop no need of it. and replace your variable jsonDictionary with myJsonDictionary so to retrieve values.
// for(NSDictionary *jsonDictionary in myJsonArray)
Run now it will be fine. Worked for me fine
If the output was array of Dictionaries it would have been looked like this with square brackets around.
For Ex: [{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
If you are not sure of nature of response from url you can check for
the type. For ex:
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *myJsonArray = (NSArray *)jsonObject;
// Handle Array of Dictionary
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSString *address1 = jsonDictionary[#"Address1"];
//and so on
}
}
else {
NSLog(#"It's Dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
//Handle NSDictionary
}
jsonDictonary is a NSString not as you expect NSDictonary.
Double check your JSON and maybe before calling that function check if it's NSDictonary.
Your should use one of the semi-standard frameworks for parsing JSON into Core Data. There are some SO questions about those.
In this case, your JSON has only one object which is not an array.
In general, your app shouldn't abort if server sent something unexpected, so it's better to use a parser which will loudly complain about malformed JSON than with it from scratch.
I am trying to create an autocomplete addresses suggestion using JSON.
The problem that I am facing is that I can get the latitude and longitude from a the user types on the UISearchDisplay. However I am trying to parse this data to addresses names. I was trying to use reverse geocoding from Apple but with no success. I am receiving only one value.
I was using apple geocoding straight away but the results were not what I was expecting.
Here is the code:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
NSError *error;
NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true", self.searchBar.text];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
self.locationArray = [[[jsonDict valueForKey:#"results"] valueForKey:#"geometry"] valueForKey:#"location"];
int total = self.locationArray.count;
for (int i = 0; i < total - 1; i++)
{
NSLog(#"locationArray count: %d", self.locationArray.count);
NSArray *localLocations;
localLocations = [self.locationArray objectAtIndex:i];
NSLog(#"%d",i);
NSString *latitudeString = [localLocations valueForKey:#"lat"];
NSString *longitudeString = [localLocations valueForKey:#"lng"];
NSLog(#"LatitudeString:%# & LongitudeString:%#", latitudeString, longitudeString);
NSString *statusString = [jsonDict valueForKey:#"status"];
NSLog(#"JSON Response Status:%#", statusString);
double latitude = 0.0;
double longitude = 0.0;
latitude = [latitudeString doubleValue];
longitude = [longitudeString doubleValue];
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error){
[[self placemarks] addObject:placemarks];
NSLog(#"PLACEMARKS %d", self.placemarks.count);
}];
}
NSLog(#"Mutable array %d", self.placemarks.count);
[self.searchDisplayController.searchResultsTableView reloadData];
return NO;
}
The NSLog(#"PLACEMARKS %d", self.placemarks.count); only display once, in the end of the task.
Any suggestions?
I really was doing so much more than the necessary.
Here is my code now:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
NSError *error;
NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&components=country:AU&sensor=false", self.searchBar.text];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
self.locationArray = [[jsonDict valueForKey:#"results"] valueForKey:#"geometry"];
int total = self.locationArray.count;
NSLog(#"locationArray count: %d", self.locationArray.count);
for (int i = 0; i < total; i++)
{
NSString *statusString = [jsonDict valueForKey:#"status"];
NSLog(#"JSON Response Status:%#", statusString);
NSLog(#"Address: %#", [self.locationArray objectAtIndex:i]);
}
[self.searchDisplayController.searchResultsTableView reloadData];
return NO;
}