I am retrieving data from a mysql database and want to display it in a textview. So, I created a for loop for each piece of data. The problem is it only creates one textview and therefore only displays the first piece of retrieved data. My code is below:
-(void) getData:(NSData *) data {
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
-(void) start {
//NSLog(#"%lu", (unsigned long)[json count]);
NSURL *url = [NSURL URLWithString:kGETUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
NSIndexPath *indexPath;
NSDictionary *info = [json objectAtIndex:indexPath.row];
for (int i = 0; i < [json count]; i++)
{
//NSLog(#"%#", json);
UITextView *myTextView = [[UITextView alloc] init];
myTextView.text = [info objectForKey:#"title"];
[self.view addSubview:myTextView];
[myTextView sizeToFit];
}
}
json is an array and info is one dictionary in json.
You are looping five times over json but printing the same info. You need:
int yPos = 0;
for (int i = 0; i < [json count]; i++)
{
//NSLog(#"%#", json);
info = [json objectAtIndex:i];
UITextView *myTextView = [[UITextView alloc] init];
myTextView.text = [info objectForKey:#"title"];
[self.view addSubview:myTextView];
[myTextView sizeToFit];
yPos += myTextView.frame.size.height;
myTextView.frame = CGRectMake(0, yPos, myTextView.frame.size.width, myTextView.frame.size.height);
}
Related
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
I have the json data were within the first array I main category array with name "Response" within that I have parent category array with name "0" within which I have child category array with name "0" and here is my json format
{"Response":[{"menuname":"Jewellery","menuid":"1","0":[{"catname":"Rings","catid":"1","0":[{"scatname":"Engagement Rings","scatid":"4"},{"scatname":"Wedding Rings","scatid":"5"},{"scatname":"kk","scatid":"35"}]},{"catname":"Pendants","catid":"2","0":[{"scatname":"Office Wear","scatid":"8"}]},{"catname":"Bracelets","catid":"3","0":[{"scatname":"Studded","scatid":"9"}]},{"catname":"Earrings","catid":"6","0":[{"scatname":"Ethnic Jhumkas","scatid":"7"}]},{"catname":"Chain's","catid":"33","0":[]},{"catname":"Jewel","catid":"34","0":[]}]},{"menuname":"Collections","menuid":"2","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"Gold Coin","menuid":"3","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"OFF THE SHELF","menuid":"4","0":[{"catname":"testing from pixel","catid":"13","0":[]},{"catname":"New pixel","catid":"23","0":[]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]}]}
and I want to display in expandable tableview as below
Jewellery
Rings
Engagement Rings
Wedding Rings
kk
Pendants
Ofice Wear
Collections
Sound Of Love
Love bracelet
Colorful Affair
Passion ring
Here is the code I used in viewdidLoad
NSDictionary *pJson;
NSMutableString *postStr = [NSMutableString stringWithString:kURL];
[postStr appendString:[NSString stringWithFormat:#"?tag=%#&id=%#",kCategoryFilter,kPrecious]];
[postStr setString:[postStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:postStr]];
NSLog(#"%#",postStr);
[request setHTTPMethod:#"POST"];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
NSURL *url = [NSURL URLWithString:postStr];
NSData *data = [NSData dataWithContentsOfURL:url];
pJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"%#",pJson);
NSMutableArray *arr = [pJson objectForKey:#"Response"];
NSLog(#"%lu",(unsigned long)arr.count);
NSMutableDictionary *dict2 =[[NSMutableDictionary alloc]init];// [arr objectAtIndex:NSIndexPath.row];
[dict2 setObject:arr forKey:#"dictionary1"];
dict2 = [arr objectAtIndex:0];
NSArray *arr1 =[dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
NSUInteger y;
for (int i=0;i<arr.count;i++) {
NSString *ring_data = [[arr objectAtIndex:i]objectForKey:#"menuname"];
NSString *id_data = [[arr objectAtIndex:i]objectForKey:#"menuid"];
NSLog(#"AUTHOR: %#",ring_data);
NSLog(#"%#",id_data);
dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"menuname",id_data,#"menuId",nil];
[myObject addObject:dictionary];
NSMutableArray *arr1 = [dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
y = arr.count;
for (NSUInteger i=0;i<arr1.count;i++) {
NSArray *count = [[[arr1 objectAtIndex:i] objectForKey:arr]valueForKey:#"catname"];
NSString *myCount = [NSString stringWithFormat:#"%lu",(unsigned long)[count count]];
NSString *ring_data = [[arr1 objectAtIndex:i]objectForKey:#"catname"];
NSLog(#"AUTHOR: %#",ring_data);
// NSLog(#"%#",catname_data);
dictionary1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"catname",
nil];
[myObject1 addObject:dictionary1];
}
}
I tried some coding for you.Follow that code and customize where you want to add to array and where to set dictionary.
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[jsonArray objectForKey:#"Response"];
for (int i=0;i<[array count];i++)
{
NSMutableDictionary *dict = [array objectAtIndex:i];
NSMutableArray *arrayDictValue = [dict valueForKey:[NSString stringWithFormat:#"%d",0]];
NSString *strMenuName = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuname"]];
NSString *strMenuID = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuid"]];
NSLog(#"The strMenuName is-%#",strMenuName);
NSLog(#"The strMenuID is-%#",strMenuID);
for (int j=0; j<[arrayDictValue count]; i++)
{
NSMutableDictionary *dictInside = [arrayDictValue objectAtIndex:j];
NSArray *arrayInsideDict = [dictInside valueForKey:#"0"];
for (int k =0; k<[arrayInsideDict count]; i++)
{
NSString *strCatName = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catname"]];
NSString *strCatID = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catid"]];
NSLog(#"The strCateName is-%#",strCatName);
NSLog(#"The strCatID is-%#",strCatID);
NSMutableDictionary *dictInArray = [[arrayInsideDict objectAtIndex:0] valueForKey:#"0"];
NSString *strSCatName = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatname"]];
NSString *strSCatID = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatid"]];
NSLog(#"the strSCatName is - %#",strSCatName);
NSLog(#"the strSCatID is - %#",strSCatID);
}
}
}
i have code to display a single image from json array data in a UIImageView.
i want to display all images in multiple UIImageViews.
plz suggest me how to loop images to display all.
json array data link:
Here's code from my app
NSString *urlString=[NSString stringWithFormat:#"http://ielmo.xtreemhost.com/array.php"];
NSURL * url=[NSURL URLWithString:urlString];
NSData *data =[NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableArray *json=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",[json objectAtIndex:0]);
NSString *imageString=[NSString stringWithFormat:#"%#",[json objectAtIndex:0]];
NSURL * urlone=[NSURL URLWithString:imageString];
NSData *datanew =[NSData dataWithContentsOfURL:urlone];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)];
[imageView setImage:[UIImage imageWithData:datanew]];
testView = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 300.0f, 300.0f, 200.0f)];
[testView addSubview:imageView];
[self.view addSubview:testView];
NSMutableArray *arr=[[NSMutableArray alloc] init];
NSString *urlString=[NSString stringWithFormat:#"http://ielmo.xtreemhost.com/array.php"];
NSURL * url=[NSURL URLWithString:urlString];
NSData *data =[NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableArray *json=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%d",[json count]);
NSLog(#"%#",[json objectAtIndex:0]);
NSString *imageString;
for (int i=0; i<[json count]; i++) {
imageString=[NSString stringWithFormat:#"%#",[json objectAtIndex:i]];
[arr addObject:imageString];
}
NSLog(#"%#",arr);
// NSString *imageString=[NSString stringWithFormat:#"%#",[json objectAtIndex:0]];
NSURL * urlone=[NSURL URLWithString:imageString];
NSData *datanew =[NSData dataWithContentsOfURL:urlone];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)];
[imageView setImage:[UIImage imageWithData:datanew]];
UIView * testView = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 300.0f, 300.0f, 200.0f)];
[testView addSubview:imageView];
[self.view addSubview:testView];
After parsing JSON response use follow code
UIScrollView *testView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,320,480)];
for(int i=0; i<[json count]; i++){
NSLog(#"%#",[json objectAtIndex:i]);
NSString *imageString=[NSString stringWithFormat:#"%#",[json objectAtIndex:i]];
NSURL * urlone=[NSURL URLWithString:imageString];
NSData *datanew =[NSData dataWithContentsOfURL:urlone];*
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,i*480,320,480)];
[imageView setImage:[UIImage imageWithData:datanew]];
[testView addSubview:imageView];
}
[self.view addSubView:testView];
*Note: Now you are going with Synchronous Request to download & load images in the view. It is not a good approach. Use Asynchronous requests for downloading images and loading them.
Find the following URL for asynchronous image downloading
Asynchronous downloading of images for UITableView with GCD
you can get an image dictionary into array like this, into data object
Suppose i have PostClubDC class with posDC obj
for(NSDictionary *returnDicto in dataArray)
{
PostClubDC *postDC = [[PostClubDC alloc] init];
NSDictionary * returnDict = [returnDicto objectForKey:#"club_info"] ;
postDC.postID = [[returnDict objectForKey:#"Id"]integerValue];
postDC.postName = [returnDict objectForKey:#"name"];
postDC.postImage = [returnDict objectForKey:#"image"];
[yourDataArray addObject:postDC];
}
I'm having a trouble dynamically adding UIButtons with background image as subviews to a UIScrollView. Its kind of a image gallery using UIButtons on a scrollView. I have used this method for couple of my apps, it works fine for me with the static contents.
But this time, Im loading images from a web service and saved to documents directory, then call the method to create the gallery. Logic is same with my other apps. But I cannot figure out what is the issue here.
I'll put here both the codes one is for retrieving data and other is the creating gallery.
Data retrieving from server
-(void)loadDataFromServer{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
arrCats = [[NSMutableArray alloc]init];
arrPromos = [[NSMutableArray alloc]init];
//[spinMenu startAnimating];
// load promo images from the server
for(int i=0;i<[arrPromos count];i++)
{
NSString *urlString = [Constants getImages:[[arrPromos objectAtIndex:i] objectForKey:#"image"]];
NSLog(#"Get Images API Call : %#", urlString);
NSURL *imageurl = [NSURL URLWithString:urlString];
//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageurl];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
if(imageData != nil){
// save the images temporally
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:[[arrPromos objectAtIndex:i] objectForKey:#"image"]]; //Add the file name
[imageData writeToFile:filePath atomically:YES];
}
});
});
}
// Load promotions from server
dispatch_async(queue, ^{
NSLog(#"Promotions Loading Started");
NSString *urlString = [Constants getAllPromotions:#"GetPromo.php"];
NSLog(#"Get Promotions API Call : %#", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Specify that it will be a GET request
request.HTTPMethod = #"GET";
[request setHTTPShouldHandleCookies:NO];
NSURLResponse *responseURL;
NSError *error;
NSData *dataPromotions = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseURL error:&error];
if (responseURL == nil)
{
// Check for problems
if (error != nil)
{
NSLog(#"Get Promtions Connection failed! Error - %#", [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection Error!" message:#"Promotions data failed to load!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
NSString *responseString = nil;
responseString = [[NSString alloc] initWithData:dataPromotions encoding:NSUTF8StringEncoding];
if ([responseString rangeOfString:#"error"].location == NSNotFound)
{
NSDictionary *response = [[NSDictionary alloc] init];
response = (NSDictionary *)[responseString JSONValue];
NSLog(#"Response : Promotions %#", response);
if(response != Nil){
if([response count]>0){
arrPromos = [NSMutableArray arrayWithArray:[response objectForKey:#"Promos"]];
NSLog(#"ArrPromos # loading %#", arrPromos);
// create promos galley
[self createPromosGallery];
}
}
}
}
});
Note: [self createPromosGallery]; is calling after download all the images and data.
Create Gallery
-(void) createPromosGallery{
// sort arrPromos based on priority
for(int i=0; i<[arrPromos count];i++){
[arrPromos sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDictionary *dict1 = obj1;
NSDictionary *dict2 = obj2;
NSString *string1;
NSString *string2;
if(![[dict1 objectForKey:#"priority"] isKindOfClass: [NSNull class]])
string1 = [dict1 objectForKey:#"priority"];
if(![[dict2 objectForKey:#"priority"] isKindOfClass: [NSNull class]])
string2 = [dict2 objectForKey:#"priority"];
return [string1 compare:string2 options:NSNumericSearch];
}];
}
NSLog(#"ArrPromos %#", arrPromos);
// scrollView size
CGFloat screenHieght = [UIScreen mainScreen].bounds.size.height;
if(screenHieght>500){
scrollView.frame = CGRectMake(0, 0, 320, 568);
}
else{
scrollView.frame = CGRectMake(0, 0, 320, 480);
}
// define scrollview height
int scrollHieght;
scrollHieght = ([arrPromos count]-1)/2;
NSLog(#"Scroll height %d",scrollHieght);
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width , scrollHieght * 160 +200);
scrollView.pagingEnabled = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.decelerationRate = UIScrollViewDecelerationRateFast;
scrollView.delegate = self;
for(int i=0;i<[arrPromos count];i++)
{
float x;
float y;
if(i%2==0)
{
x=30.0;
y=(i/2)*160+25;
}
if(i%2==1) {
x=170.0;
y=(i/2)*160+25;
}
// retreive saved images
NSString *strImgName;
UIImage *buttonUpImage;
// create buttons
button = [UIButton buttonWithType:UIButtonTypeCustom];
strImgName = [[arrPromos objectAtIndex:i] objectForKey:#"image"];
NSLog(#"Button image name %#", strImgName);
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#",docDirectory,strImgName];
buttonUpImage = [UIImage imageWithContentsOfFile:filePath];
[button setBackgroundImage:buttonUpImage forState:UIControlStateNormal];
button.frame = CGRectMake(x, y, 120,140);
[button setTag:i];
[button addTarget:self action:#selector(promoBtnPressed:)forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
}
}
Note: I tested on both iOS 7 and 6. In iOS 7, it takes very long time to appear images on scrollView(Currently have only 2 images). Or else, If I TAP on scroolView then the images appear.
In ios 6, nothing appear
//Make a method that has url (fileName) Param
NSArray *documentsDirectory =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSFileManager *fileManager =[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:textPath])
{
return YES;
}
else
{
return NO;
}
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage
imageNamed:#""]];//Placeholder image
if ([url isKindOfClass:[NSString class]])
{
imgView.image = [UIImage imageNamed:[url absoluteString]];
imgView.contentMode = UIViewContentModeScaleAspectFit;
}
else if ([fileManager fileExistsAtPath:url])
{
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfFile:textPath options:NSDataReadingMappedIfSafe error:&error];
if (error != nil)
{
DLog(#"There was an error: %#", [error description]);
imgView.image=nil;
}
else
{
imgView.image= [UIImage imageWithData:fileData]
}
}
else
{ UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGPoint center = imgView.center;
// center.x = imgView.bounds.size.width / 2;
spinner.center = center;
[spinner startAnimating];
[imgView addSubview:spinner];
dispatch_queue_t downloadQueue = dispatch_queue_create("iamge downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *imgData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
[spinner removeFromSuperview];
UIImage *image = [UIImage imageWithData:imgData];
NSError *error = nil;
[imgData writeToFile:url options:NSDataWritingFileProtectionNone error:&error];
if (error != nil)
}
else
{
}
imgView.image = image;
});
});
}
Thats UIImageView loading an image if it doesnot exist in document then it Save it , An Activity indicator is added to show image is loading to save,
Yes it is because you are downloading and then saving the images which takes time. I suggest you to use any library for downloading images and saving them.
Ex : SDWebImage
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.