exc_bad_access when using a async request - iphone

Im making a async request but when I try to parse it with this code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *missionsDict = [responseString JSONValue];
/*NSArray *luckyNumbers = [json objectWithString:responseString error:&error];*/
NSLog(#"user Info array is: %#", missionsDict);
// NSDictionary *array = [luckyNumbers1 objectForKey:#"data"];
NSDictionary *missionsData;
missionsData = [missionsDict objectForKey:#"data"];
NSLog(#"missionsData is: %#", missionsData);
NSEnumerator *inner = [missionsData objectEnumerator];
UIScrollView *missionsScroll;
missionsScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
missionsScroll.contentSize = CGSizeMake(320, 1005);
[self.view addSubview:missionsScroll];
id value;
int badgeY1;
int badgeY2;
int badgeY3;
badgeY1 = 121;
badgeY2 = 161;
badgeY3 = 150;
while((value = [inner nextObject])) {
NSLog(#"progress is: %#", [value objectForKey:#"progress"]);
NSLog(#"user Info array is: %#", missionsDict);
NSLog(#"name is: %#",[value objectForKey:#"reward_definitions"]);
NSLog(#"missionsData is: %#", missionsData);
NSDictionary *moreData;
moreData = [value objectForKey:#"reward_definitions"];
NSEnumerator *inner = [moreData objectEnumerator];
id value2;
int badgeX;
badgeX = 10;
while((value2 = [inner nextObject])) {
UIProgressView *progressView;
progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, badgeY3, 372, 9)];
float progressValue;
progressValue = ([[[value objectForKey:#"progress"] objectForKey:#"earned"] floatValue] / [[[value objectForKey:#"progress"] objectForKey:#"possible"] floatValue]);
NSLog(#"progressValue is: %f", progressValue);
[progressView setProgress:progressValue];
[missionsScroll addSubview:progressView];
UILabel *missionName;
missionName = [[UILabel alloc] initWithFrame:CGRectMake(20, badgeY1, 280, 25)];
missionName.backgroundColor = [UIColor clearColor];
missionName.textColor = [UIColor whiteColor];
missionName.font = [UIFont fontWithName:#"Heiti TC" size:23.0];
missionName.text = [value objectForKey:#"name"];
[missionsScroll addSubview:missionName];
NSLog(#"badgeY2 is: %#", badgeY2);
badgesScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, badgeY2, 318, 70)];
badgesScroll.contentSize = CGSizeMake(320, 70);
[missionsScroll addSubview:badgesScroll];
NSLog(#"Image URL is: %#", [value2 objectForKey:#"image_url"]);
NSURL *url1 = [NSURL URLWithString: [NSString stringWithFormat:#"%#", [value2 objectForKey:#"image_url"]]];
NSData *urlData1 = [NSData dataWithContentsOfURL:url1];
UIImage *image1 = [UIImage imageWithData:urlData1];
UIImageView *badge = [[UIImageView alloc] initWithImage:image1];
[badge setFrame:CGRectMake(badgeX, -10, 70, 70)];
[badgesScroll addSubview:badge];
[badge release];
badgeCount = badgeCount+1;
badgeX = badgeX +80;
}
// NSLog(#"reward_definitions is: %#", [missionsData objectForKey:#"id"]);
// NSLog(#"Image URL is: %#", [[value objectForKey:#"reward_definitions"] objectForKey:#"image_url"]);
//if ( [array isKindOfClass:[NSDictionary class]] ) {
badgeY1 = badgeY1 +100;
badgeY2 = badgeY2 +100;
badgeY3 = badgeY3 +100;
missionCount = missionCount+1;
}
for (int b; badgeCount > 4; b = b+1) {
[badgesScroll setContentSize:CGSizeMake(badgesScroll.contentSize.width+80, badgesScroll.contentSize.height)];
}
for (int a; missionCount > 4; a = a+1) {
missionsScroll.contentSize = CGSizeMake(776, missionsScroll.contentSize.height+200);
}
}
It crashes because of EXC_BAD_ACCESS on NSLog(#"badgeY2 is: %#", badgeY2);

your badgeY2 contains an integer value. To print the integer value with NSLog, you must use %d
You should always keep it in mind while using NSLog, what kind of value it returns!
NSLog(#"badgeY2 is: %d", badgeY2);
There is another heck solution to just let you know
NSLog(#"%#", [NSNumber numberWithInt:badgeY2]);
These are the NSLog format specifiers :
%# Object
%d, %i signed int
%u unsigned int
%f float/double
%x, %X hexadecimal int
%o octal int
%zu size_t
%p pointer

Should be
NSLog(#"badgeY2 is: %i", badgeY2);
badgeY2 is an int, so you must use %i instead of %#

Related

print nsmutable array using printer in ios

I have three nsmutable array in ios. I have to print data as below example using printer , How should i do it?
example:--
0.5 1 10
1 10 11
2 5 22
3 4 6
For example these are arrays :
NSArray *arr = [NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6", nil];
NSArray *arr1 = [NSArray arrayWithObjects:#"17",#"27",#"37",#"47",#"57",#"67", nil];
NSArray *arr2 = [NSArray arrayWithObjects:#"171",#"271",#"371",#"471",#"571",#"671", nil];
Now get all data in NSString
NSMutableString *str = [NSMutableString string];
for (int i=0; i<[arr count]; i++)
{
str = [str stringByAppendingFormat:[NSString stringWithFormat:#"%# %# %#\n",[arr objectAtIndex:i],[arr1 objectAtIndex:i],[arr2 objectAtIndex:i]]];
}
NSLog(#"%#",str);
Use toPdfData method to get NSData to print.
NSData *data = [self toPdfData:str];
Add these method:
- (NSData *) toPdfData :(NSMutableString *)str
{
//calculate size
CGSize stringSize = [str sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320 , 999) lineBreakMode:UILineBreakModeWordWrap];
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0, 0, stringSize.width, stringSize.height), nil);
UIGraphicsBeginPDFPage();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[str drawInRect:CGRectMake(0, 0, stringSize.width, stringSize.height) withFont:[UIFont systemFontOfSize:15]];
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
return pdfData;
}
EDIT : Now you have PDF Data and PDF file also store in NSDocument Directory so print using UIPrintInteractionController
You can use the UIPrintInteractionController for doing this.
Please check the below code:
NSMutableString *stringToPrint = [[NSMutableString alloc] initWithString:#""];
for(int i = 0;i<[array count];i++)
{
[stringToPrint appendFormat:#"%#",[array objectAtIndex:i]];
if(i%2 == 0)
{
[stringToPrint appendFormat:#"\n"];
}
else
{
[stringToPrint appendFormat:#"\t"];
}
}
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = #"Midhun";
pic.printInfo = printInfo;
UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc]
initWithText:stringToPrint];
textFormatter.startPage = 0;
textFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0); // 1 inch margins
textFormatter.maximumContentWidth = 6 * 72.0;
pic.printFormatter = textFormatter;
pic.showsPageRange = YES;
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *printController, BOOL completed, NSError *error)
{
if (!completed && error)
{
NSLog(#"Printing could not complete because of error: %#", error);
}
};
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
[pic presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
}
else
{
[pic presentAnimated:YES completionHandler:completionHandler];
}
Please read Printing and Drawing in iOS for more details.
Use following code to traverse and print.
for (int i=0; i<[array count]; i++) {
NSLog(#"%#",[array objectAtIndex:i]);
}

How to Access Particular view of a pageControl viewController?

Hi I m creating a project where multiple Images Loading from Server With some like Count and Comment Count and a Button to like the image. I m showing the individual Images With using a Slider Controller like PageControl.
this is My code for Showing the View
-(UIView*)reloadView:(DPSliderView *)sliderView viewAtIndex:(NSUInteger)idx
{
_loading_view.hidden=TRUE;
if (idx < [photos count]) {
NSDictionary *item = [photos objectAtIndex:idx];
PhotoView *v = [[PhotoView alloc] init];
v.photoIndex = idx;
v.imageView.imageURL = [DPAPI urlForPhoto:item[#"photo_220x220"]];
NSString *placename1 = [item valueForKeyPath:#"spotting.item.name"];
NSString *firstCapChar1 = [[placename1 substringToIndex:1] capitalizedString];
NSString *cappedString1 = [placename1 stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar1];
v.spotNameLabel.text = cappedString1;
NSString *placename = [item valueForKeyPath:#"spotting.place.name"];
NSString *firstCapChar = [[placename substringToIndex:1] capitalizedString];
NSString *cappedString = [placename stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
NSString *place1=[NSString stringWithFormat:#"%#",cappedString];
NSString *address=[NSString stringWithFormat:#"%#",[item valueForKeyPath:#"spotting.place.address"]];
NSString *location_str3 = [NSString stringWithFormat:#"# %#, %#",place1,address];
int cap_len=[place1 length];
int address_lenth=[address length];
ZMutableAttributedString *str = [[ZMutableAttributedString alloc] initWithString:location_str3
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
[[FontManager sharedManager] zFontWithName:#"Lucida Grande" pointSize:12],
ZFontAttributeName,
nil]];
[str addAttribute:ZFontAttributeName value:[[FontManager sharedManager] zFontWithName:#"Lucida Grande" pointSize:12] range:NSMakeRange(0, cap_len+3)];
[str addAttribute:ZForegroundColorAttributeName value:[UIColor colorWithRed:241/255.0f green:73.0/255.0f blue:2.0/255.0f alpha:1.0]range:NSMakeRange(0, cap_len+3)];
[str addAttribute:ZForegroundColorAttributeName value:[UIColor colorWithRed:128.0/255.0f green:121.0/255.0f blue:98.0/255.0f alpha:1.0]range:NSMakeRange(cap_len+4, address_lenth)];
v.placefontlabel.zAttributedText=str;
v.likesCountLabel.text = [NSString stringWithFormat:#"%i", [item[#"likes_count"] intValue]];
if ([_device_lang_str isEqualToString:#"es"])
{
v.shightingsLabel.text = [NSString stringWithFormat:NSLocalizedString(#"%i Vistas", nil), [item[#"sightings_count"] intValue]];
}
else
{
v.shightingsLabel.text = [NSString stringWithFormat:NSLocalizedString(#"%i Sightings", nil), [item[#"sightings_count"] intValue]];
}
if ([nolocationstr isEqualToString:#"YES"])
{
v.distanceLabel.text =[NSString stringWithFormat:#"%.2f km", [item[#"distance"] floatValue]];
}
else
{
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:[[item valueForKeyPath:#"spotting.place.lat"]floatValue] longitude:[[item valueForKeyPath:#"spotting.place.lng"] floatValue]];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:[_explore_lat_str floatValue] longitude:[_explore_lng_str floatValue]];
NSString *lat_laong=[NSString stringWithFormat:#"%f",[location1 distanceFromLocation:location2]];
int km=[lat_laong floatValue]*0.001;
NSString *distancestr=[NSString stringWithFormat:#"%d km",km];
float dist=[distancestr floatValue];
v.distanceLabel.text = [NSString stringWithFormat:#"%.2f km", dist];
}
if (![item[#"likes"] boolValue]) {
v.likeButton.enabled = YES;
v.likeButton.tag = idx;
[v.likeButton setImage:[UIImage imageNamed:#"like_new.png"] forState:UIControlStateNormal];
[v.likeButton addTarget:self action:#selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
}
else
{
v.likeButton.tag = idx;
[v.likeButton setImage:[UIImage imageNamed:#"like_new1.png"] forState:UIControlStateNormal];
}
NSArray *guides = item[#"guides"];
if ([guides count] > 0) {
NSString *guideType = [[guides objectAtIndex:0] valueForKey:#"type"];
UIImage *guidesIcon = [UIImage imageNamed:[NSString stringWithFormat:#"%#.png", guideType]];
v.guideButton.hidden = NO;
v.guideButton.tag = idx;
[v.guideButton setImage:guidesIcon forState:UIControlStateNormal];
[v.guideButton addTarget:self action:#selector(guideAction:) forControlEvents:UIControlEventTouchUpInside];
}
v.shareButton.tag = idx;
[v.shareButton addTarget:self action:#selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(photoTapGesture:)];
[v addGestureRecognizer:tapGesture];
[tapGesture release];
return [v autorelease];
} else {
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"sc_img.png"]];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.center = CGPointMake(CGRectGetMidX(iv.bounds), 110);
[indicator startAnimating];
[iv addSubview:indicator];
[indicator release];
return [iv autorelease];
}
}
Now My question is :
If i will Click on Like Button , Then i have to change the button image as well as like count. I can able to Change the Button Image By This Method
[sender setImage:[UIImage ImageNamed:#"image.png"]];
But How can I change the Like count of the Label ? How can i access the Particular label of the View ? I have assigned the tag But , I dont know how to assign it.I dont want to Reload Whole Slider as the Photo are loading from Network (Remote Server) . Thanks for your Time.
Just keep a reference to the label and update that.
// #interface
#property (nonatomic, strong) UILabel *myLabel;
// #implementation
_myLabel.text = #"Whatever.";
If you have multiple labels, set the tags when you create your views
newView.tag = sequenceNumber +100;
And then update
-(void)updateLabelWithTag:(NSInteger)tag {
UILabel *label = (UILabel*) [self.scrollView viewWithTag:tag];
label.text = #"Whatever.";
}

Load more pages in TTLauncherView

In my implementation of TTLauncherView, only loads the first page. Why?
I have 47 items in array, 47 items div 9 items by page, I should have 6 pages.
Thanks for helping.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSMutableString *jsonString = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
NSArray *photos = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
launcherView = [[TTLauncherView alloc] initWithFrame:self.view.bounds];
launcherView.backgroundColor = [UIColor whiteColor];
launcherView.delegate = self;
launcherView.columnCount = 3;
launcherView.persistenceMode = TTLauncherPersistenceModeNone;
NSMutableArray *itemArray = [[NSMutableArray alloc] init];
for (NSDictionary *photo in photos)
{
NSString *iconURLString = [NSString stringWithFormat:#"http://farm%#.static.flickr.com/%#/%#_%#_s.jpg",
[photo objectForKey:#"farm"], [photo objectForKey:#"server"], [photo objectForKey:#"primary"], [photo objectForKey:#"secret"]];
NSDictionary *title = [photo objectForKey:#"title"];
NSString *itemTitle = [title objectForKey:#"_content"];
TTLauncherItem *itemMenu = [[[TTLauncherItem alloc] initWithTitle:itemTitle
image:iconURLString
URL:nil
canDelete:NO] autorelease];
[itemArray addObject:itemMenu];
}
launcherView.pages = [NSArray arrayWithObject: itemArray];
[self.view addSubview:launcherView];
}
As I recall, TTLauncherView doesn't break up the TTLauncherItem's into pages automatically. You need an array of arrays. All of the launcher item's in the first array will be on the first page, all the launcher item's in the second array will be on the second page etc. It has been a long time since I've used it, but I think that's how it worked.
My modified code with the hint of #Darren
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSMutableString *jsonString = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
NSArray *photos = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
NSMutableArray *itemArray = [[NSMutableArray alloc] init];
NSMutableArray *pageArray = [[NSMutableArray alloc] init];
NSNumber *countPage = [[NSNumber alloc] initWithInt:0];
for (NSDictionary *photo in photos)
{
NSString *iconURLString = [NSString stringWithFormat:#"http://farm%#.static.flickr.com/%#/%#_%#_s.jpg",
[photo objectForKey:#"farm"], [photo objectForKey:#"server"], [photo objectForKey:#"primary"], [photo objectForKey:#"secret"]];
NSString *photoCount = [photo objectForKey:#"photos"];
NSDictionary *title = [photo objectForKey:#"title"];
NSString *itemTitle = [title objectForKey:#"_content"];
TTLauncherItem *itemMenu = [[[TTLauncherItem alloc] initWithTitle:itemTitle
image:iconURLString
URL:nil
canDelete:NO] autorelease];
itemMenu.badgeValue = photoCount;
[itemArray addObject:itemMenu];
int value = [countPage intValue];
countPage = [NSNumber numberWithInt:value + 1];
if (countPage == [NSNumber numberWithInt:9]){
countPage = [NSNumber numberWithInt:0];
[pageArray addObject:itemArray];
itemArray = [[NSMutableArray alloc] init];
}
}
[pageArray addObject:itemArray];
launcherView = [[TTLauncherView alloc] initWithFrame:self.view.bounds];
launcherView.backgroundColor = [UIColor blackColor];
launcherView.delegate = self;
launcherView.columnCount = 3;
launcherView.persistenceMode = TTLauncherPersistenceModeNone;
launcherView.pages = pageArray;
[self.view addSubview:launcherView];
}

iphone+UIscrollview or to use uitableview to display image in matrix format

I want to display the image(which comes from webservice) the format such that the output in the screen appears like below image:-
Now the logic i had implemented is,i had added the image in uiscrollview.
with the below logic:-
for (int j=0;j<9;j++) {
for (int i=0; i<[mainRestaurantArray count];i++) {
if ([[[mainRestaurantArray objectAtIndex:i] valueForKey:#"Image"] isKindOfClass:[UIImage class]]) {
[CombineArray addObject:[mainRestaurantArray objectAtIndex:i]];
//NSLog(#"cnt=>%d array==>%#",cnt,[CombineArray objectAtIndex:cnt]);
UIButton* btn = [[UIButton alloc]init];
btn.tag = cnt;
btn.frame = CGRectMake(15+(cnt%5)*60, 15+(cnt/5)*60,Width,Height);
btn.backgroundColor = [UIColor greenColor];
[btn setBackgroundImage:[[CombineArray objectAtIndex:cnt] valueForKey:#"Image"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(Buttonclick:) forControlEvents:UIControlEventTouchUpInside];
[ScrlPhotos addSubview:btn];
[btn release];
cnt++;
}
}
[mainRestaurantArray release];
counter++;
[self urlcalled];//The function which calls the webservice
}
//}
ScrlPhotos.contentSize = CGSizeMake(320, ([CombineArray count]/5.0)*60+25);
The function which does the webservice is below:-
-(void)urlcalled{
#try
{
if (rangeDistance == nil) {
rangeDistance =#"100";
}
urlstring[0]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Gym&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[1]=[NSString stringWithFormat:#"http://www.google.com/maps?q=resort&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[2]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Tourist place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[3]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Hotels&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[4]=[NSString stringWithFormat:#"http://www.google.com/maps?q=shopping Mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[5]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Industries&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[6]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Shopping_mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[7]=[NSString stringWithFormat:#"http://www.google.com/maps?q=garden&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[8]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Religious Place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[9]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Restaurants&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
NSLog(#"conte==>%d urlstring[counter]==>%#",counter,urlstring[counter]);
NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlstring[counter]]];
str1 = [str substringFromIndex:9];
//NSLog(#"===>%#",str1);
NSArray *array = [str1 componentsSeparatedByString:#"overlays:"];
NSString *str2 = [array objectAtIndex:1];
NSString *finalUpperStr = [str2 substringFromIndex:21];
array1 = [finalUpperStr componentsSeparatedByString:#"},panel:"];
NSString *strF = [array1 objectAtIndex:0];
NSArray *arrayF = [strF componentsSeparatedByString:#"{id:"];
///////....................this object will change as require in for loop .............................//
mainRestaurantArray = [[NSMutableArray alloc] init];
for (int i=1; i<[arrayF count]-5; i++) {
NSString *strF12 = [arrayF objectAtIndex:i];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSArray *aryF23 = [strF12 componentsSeparatedByString:#"latlng:{"];
//NSLog(#"%#",[aryF23 objectAtIndex:1]);
NSString *strF23 = [aryF23 objectAtIndex:1];
NSArray *ar = [strF23 componentsSeparatedByString:#"},image:"];
//NSLog(#"%#",[ar objectAtIndex:0]);
NSString *strLat = [ar objectAtIndex:0];
NSArray *arrayLat = [strLat componentsSeparatedByString:#","];
NSString *strFLat = [[arrayLat objectAtIndex:0] substringFromIndex:4];
NSString *strLong = [[arrayLat objectAtIndex:1] substringFromIndex:4];
//NSLog(#"Lati = %# Longi = %#" , strFLat , strLong);
[dic setValue:strFLat forKey:#"Latitude"];
[dic setValue:strLong forKey:#"Longitude"];
NSString *strLAdd = [ar objectAtIndex:1];
NSArray *arrayLAdd = [strLAdd componentsSeparatedByString:#"laddr:"];
//NSLog(#"%#",[arrayLAdd objectAtIndex:1]);
NSString *strLAdd1 = [arrayLAdd objectAtIndex:1];
NSArray *arrayLAdd1 = [strLAdd1 componentsSeparatedByString:#"geocode:"];
// NSLog(#"%#",[arrayLAdd1 objectAtIndex:0]);
NSString *strAddres = [[arrayLAdd1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
//NSLog(#"%#",strAddres);
[dic setValue:strAddres forKey:#"Address"];
NSString *strName = [arrayLAdd1 objectAtIndex:1];
NSArray *arrayName = [strName componentsSeparatedByString:#"name:"];
NSString *strName1 = [[arrayName objectAtIndex:1]stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *arrayName1 = [strName1 componentsSeparatedByString:#"infoWindow:"];
[dic setValue:[arrayName1 objectAtIndex:0] forKey:#"Name"];
// for image load .. 07Dec..
NSString *strImage= [arrayF objectAtIndex:i];
NSRange range = [strImage rangeOfString:#"photoUrl"];
if(range.location == NSNotFound){
NSLog(#"Not found");
[dic setValue:#"" forKey:#"Image"];
}else{
NSArray *arrayImage = [strImage componentsSeparatedByString:#"photoUrl:"];
NSString *strImage1 = [arrayImage objectAtIndex:1];
NSArray *arrayImage1 = [strImage1 componentsSeparatedByString:#",photoType:"];
NSString *strfindImage = [[arrayImage1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strfindImage]]];
[dic setValue:myImage forKey:#"Image"];
}
[mainRestaurantArray addObject:dic];
if (i==20) {
break;
}
}
}
#catch (NSException * e)
{
NSLog(#"NSException==>%#",e);
}
}
But the problem i am facing is the image is displayed after completing the loop at 10 times.
I want to display the image parallely as it comes from webservice,so that time taken should be less..
Is there any way out..
Please help me.
Use UIImageView+cacheWeb.. it makes lazy loading a lot easier
http://hackemist.com/SDWebImage/doc/Categories/UIImageView+WebCache.html

iPhone JSON - Iterate NSArray and get values

I've been trying to solve this myself (I was awake all last night banging my head against a wall) but hopefully someone here can help me.
I have used this tutorial to connect to my JSON datasource (http://www.mobileorchard.com/tutorial-json-over-http-on-the-iphone/) and it works fine but I would now like to get the values (by object key I think).
My json data is as follows:
[{"Id":"1","Name":"Richard","NameOfFile":"1.jpg"},{"Id":"395","Name":"Alex","NameOfFile":"390.jpg"}]
And the code i'm using to connect to it is as follows.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
SBJSON *json = [[SBJSON new] autorelease];
NSArray *myArray = [json objectWithString:responseString error:nil];
[responseString release];
for (int i = 0; i < [myArray count]; i++)
{
for(int colIndex = 0; colIndex < 5; colIndex++)
{
UIImage * myimage = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: #"http://www.goweruk.com/Images/Uploaded/220/873.jpg"]]];
UIImageView *myimageview = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,50.0f, 50.0f)];
[myimageview setImage:myimage];
CGRect frameRect = myimageview.frame;
frameRect.origin.x = (frameRect.size.width + 14) * colIndex;
frameRect.origin.y = (frameRect.size.height + 14) * i;
myimageview.frame = frameRect;
[self.view addSubview:myimageview];
[myimageview release];
}
}
}
So what i'd like to do is inside that loop, get an item value. Does anyone know how I would do that?
That NSArray is an array of NSDictionary objects, so you will first need to get the dictionary at the desired index using objectAtIndex:, then iterate through the dictionary using for..in:
for (int i = 0; i < [myArray count]; i++)
{
NSDictionary *dict = [myArray objectAtIndex:i];
for(NSString *key in dict) {
//do something with key or [dict objectForKey:key];
}
}