don't display image in UIScrollView - ios

I created 2 class (RecipeViewController & DetailViewController)
RecipeView is TableViewController that show me 4 cell (name of book) and DetailView is UIViewController that has UIScroll that show me many images of any book.
my problem is when I click on any cell and go to next page UIScroller dont show images to me.
this is my code:
RecipeViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int x = (indexPath.row)+1;
NSLog(#"x : %d",x);
DetailViewController *obj = [[DetailViewController alloc]init];
obj.yourValue = [NSString stringWithFormat:#"%d",(indexPath.row)+1];
[self presentModalViewController:obj animated:YES];
NSLog(#"yourValue1 : %#",obj.yourValue);
}
DetailViewController.m
#import "DetailViewController.h"
#import "RecipeViewController.h"
#implementation DetailViewController
#synthesize scroller,yourValue;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//m1 variable tell me in tableview which choice book
int m1 = [self.yourValue integerValue];
NSLog(#"m1 : %d",m1);
//this code give me number of images (pages of book)
NSString *numberbook = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.102/mamal/book.php?info=0&b=%d",m1]]];
NSInteger numbook = [numberbook integerValue];
NSLog(#"%d",numbook);
for (int i = 1; i <= numbook; i++)
{
//this code for recive images from specific book
NSData *dat = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.102/mamal/book.php?p=%d&b=%d",i,m1]]];
NSLog(#"%#",dat);
UIImageView *imagen = [[UIImageView alloc] initWithImage:[UIImage imageWithData:dat]];
imagen.frame = CGRectMake((i-1)*320, 0, 320, 460);
[scroller addSubview:imagen];
}
scroller.delegate = self;
scroller.contentSize = CGSizeMake(320*numbook, 460);
scroller.pagingEnabled = YES;
}
#end
sorry for my weak english!!!

If you really want to use [NSData dataWithContentsOfURL:]; Add this inside your loop, chnage url and the imageView frame.
for (int i = 1; i <= numbook; i++)
{
UIImageView *yourImage=[[UIImageView alloc]init];
yourImage.frame = CGRectMake((i-1)*320, 0, 320, 460);
[scroller addSubview:imagen];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.102/mamal/book.php?p=%d&b=%d",i,m1]];
NSData *imgData = [NSData dataWithContentsOfURL:url];
dispatch_sync(dispatch_get_main_queue(), ^{
UIImage *downloadedImage = [UIImage imageWithData:imgData];
yourImage.image = downloadedImage;
if(yourImage.image==nil)
{
[yourImage setImage:#"placeholder.png"];
}
});
});
}

Hey you are doing everything in the main thread and there can be a delay or some other problems generally it is not advised to do so , can you make use of NickLockWoods implementation for loading images asynchronously
https://github.com/nicklockwood/AsyncImageView
It is a very good category of UIImageView, you just have to import AsyncImageView and can use the function
[imageView setImageURL:#"ur url"];
It loads up all images asynchronously and it has so many customizations.
In your case:
for (int i = 1; i <= numbook; i++)
{
UIImageView *imagen = [[UIImageView alloc] initWithFrame: CGRectMake((i-1)*320, 0, 320, 460)];
[imagen setImageURL: [NSString stringWithFormat:#"192.168.1.102/mamal/book.php?p=%d&b=%d",i,m1]]];
[scroller addSubview:imagen];
}
You are doing everything in the main thread, that is why it is not loading images. In the same code that you are doing try giving background color of imageView and check.

Related

Setting subviews quicker than in viewDidLoad

Right now I'm allocating and initializing three UIImageViews that take up the entire screen and are stacked in the viewDidLoad method. Its actually taking some time to do this. Is there a way to do this automatically so the view just has them before its even loaded? like an init method that would speed this up?
- (void)viewDidLoad {
[super viewDidLoad];
self.mySubviews = [[NSMutableArray alloc] init];
self.videoCounterTags = [[NSMutableArray alloc] init];
int c = (int)[self.scenes count];
c--;
NSLog(#"int c = %d", c);
self.myCounter = [NSNumber numberWithInt:c];
for (int i=0; i<=c; i++) {
//create imageView
UIImageView *imageView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
[imageView setUserInteractionEnabled:YES]; // <--- This is very important
imageView.tag = i; // <--- Add tag to track this subview in the view stack
[self.view addSubview:imageView];
NSLog(#"added image view %d", i);
//get scene object
PFObject *sceneObject = self.scenes[i];
//get the PFFile and filetype
PFFile *file = [sceneObject objectForKey:#"file"];
NSString *fileType = [sceneObject objectForKey:#"fileType"];
//check the filetype
if ([fileType isEqual: #"image"])
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//get image
NSURL *imageFileUrl = [[NSURL alloc] initWithString:file.url];
NSData *imageData = [NSData dataWithContentsOfURL:imageFileUrl];
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = [UIImage imageWithData:imageData];
});
});
}
//its a video
else
{
// the video player
NSURL *fileUrl = [NSURL URLWithString:file.url];
self.avPlayer = [AVPlayer playerWithURL:fileUrl];
self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
//self.avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[self.avPlayer currentItem]];
CGRect screenRect = [[UIScreen mainScreen] bounds];
self.avPlayerLayer.frame = CGRectMake(0, 0, screenRect.size.width, screenRect.size.height);
[imageView.layer addSublayer:self.avPlayerLayer];
NSNumber *tag = [NSNumber numberWithInt:i+1];
NSLog(#"tag = %#", tag);
[self.videoCounterTags addObject:tag];
}
}
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(viewTapped:)];
// dummyScreen is just a see through view that sits on top of my image stack and holds my tap gesture recognizer
[self.view bringSubviewToFront:self.dummyScreen];
[self.dummyScreen addGestureRecognizer:tapGesture];
}
The problem is this line:
dispatch_async(dispatch_get_global_queue...
That moves you onto a background thread, and thus there is no telling when the code will be executed. Hence the delay.
If these are local files (i.e., the URL is the file URL of an image file in your app bundle), there is no need for any dispatch_async in your code. Remove all of that and do everything on the main thread. That way, it will happen as fast as possible.
If these are remote files (i.e., you have to do networking to get hold of them), then there's probably nothing you can do to speed things up; networking takes time, and viewDidLoad is just about as early as you can possibly be notified that it's time to get hold of the images.

Load remote server image in UIScrollView with NSOperatoinQueue

I want to load some "image" (In remote server) in a UIScrollView with NSOperatoinQueue. Because If I load it with normal NSURL, NSData or with NSMutableURLRequest it takes too much time to load for all the images. After that I show those images in UIButton. Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
[self startAnimation:nil];
self.imageDownloadingQueue = [[NSOperationQueue alloc] init];
self.imageDownloadingQueue.maxConcurrentOperationCount = 4; // many servers limit how many concurrent requests they'll accept from a device, so make sure to set this accordingly
self.imageCache = [[NSCache alloc] init];
[self performSelector:#selector(loadData) withObject:nil afterDelay:0.5];
}
-(void) loadData
{
adParser = [[AdParser alloc] loadXMLByURL:getXMLURL];
adsListArray = [adParser ads];
displayArray = [[NSMutableArray alloc] init];
for (AdInfo *adInfo1 in adsListArray)
{
AdInfo *adInfo2 = [[AdInfo alloc] init];
[adInfo2 setBannerIconURL:adInfo1.bannerIconURL];
[adInfo2 setBannerIconLink:adInfo1.bannerIconLink];
[displayArray addObject:adInfo2];
}
[self loadScrollView];
[activityIndicator stopAnimating];
}
-(void) loadScrollView
{
[self.scrollView setScrollEnabled:YES];
[self.scrollView setContentSize:CGSizeMake([displayArray count] * ScrollerWidth, ScrollerHight)];
for (int i = 0; i < [displayArray count]; i++)
{
adButtonOutLet = [[UIButton alloc] initWithFrame:CGRectMake(i*320, 0, ButtonWidth, ButtonHight)];
currentAd = [displayArray objectAtIndex:i];
NSString *imageUrlString = [currentAd bannerIconURL];
UIImage *cachedImage = [self.imageCache objectForKey:imageUrlString];
if (cachedImage)
{
[adButtonOutLet setImage:cachedImage forState:UIControlStateNormal];
}
else
{
[self.imageDownloadingQueue addOperationWithBlock:^
{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlString]];
UIImage *image = nil;
image = [UIImage imageWithData:imageData];
// add the image to your cache
[self.imageCache setObject:image forKey:imageUrlString];
// finally, update the user interface in the main queue
[[NSOperationQueue mainQueue] addOperationWithBlock:^
{
[adButtonOutLet setImage:image forState:UIControlStateNormal];
}];
}];
}
adButtonOutLet.userInteractionEnabled= YES;
[adButtonOutLet setTag:i];
[adButtonOutLet addTarget:self action:#selector(goToURL:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:adButtonOutLet];
}
}
Can anyone tell me what's wrong with the above code? There is no problem of parsing or retrieving data from Remote server. I check it by NSLog. I think the NSOperationQueue have some problem, which I can't manage properly. Thanks in advance. If you needed more information, I will attach here.
Have a nice day.
Not sure if this is your problem or your solution, its hard to tell without testing myself.
Taken from RayWenderlich
addOperationWithBlock: if you have a simple operation that does not
need to be subclassed, you can create an operation using the block
API. If you want to reference any object from outside in the block,
remember that you should pass in a weak reference. Also, if you want
to do something that is related to the UI in the block, you must do it
on the main thread:
// Create a weak reference
__weak MyViewController *weakSelf = self;
// Add an operation as a block to a queue
[myQueue addOperationWithBlock: ^ {
NSURL *aURL = [NSURL URLWithString:#"http://www.somewhere.com/image.png"];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:aURL options:nil error:&error];
UIImage *image = nil;
If (data)
image = [UIImage imageWithData:data];
// Update UI on the main thread.
[[NSOperationQueue mainQueue] addOperationWithBlock: ^ {
weakSelf.imageView.image = image;
}];
}];

Parsing JSON images in a background thread (AFNetworking)

I have an image slideshow with images that are being parsed with JSON and I want to run that slideshow in a background thread.
My original code:
- (void)loadVisiblePages {
// First, determine which page is currently visible
CGFloat pageWidth = self.scrollView.frame.size.width;
NSInteger page = (NSInteger)floor((self.scrollView.contentOffset.x * 2.0f + pageWidth) / (pageWidth * 2.0f));
// Update the page control
self.pageControl.currentPage = page;
// Work out which pages we want to load
NSInteger firstPage = page - 1;
NSInteger lastPage = page + 1;
// Purge anything before the first page
for (NSInteger i=0; i<firstPage; i++) {
[self purgePage:i];
}
for (NSInteger i=firstPage; i<=lastPage; i++) {
[self loadPage:i];
}
for (NSInteger i=lastPage+1; i<self.pageImages.count; i++) {
[self purgePage:i];
}
}
- (void)loadPage:(NSInteger)page {
if (page < 0 || page >= self.pageImages.count) {
// If it's outside the range of what we have to display, then do nothing
return;
}
// Load an individual page, first seeing if we've already loaded it
UIView *pageView = [self.pageViews objectAtIndex:page];
if ((NSNull*)pageView == [NSNull null]) {
CGRect frame = self.scrollView.bounds;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0.0f;
UIImageView *newPageView = [[UIImageView alloc] initWithImage:[self.pageImages objectAtIndex:page]];
newPageView.contentMode = UIViewContentModeScaleAspectFit;
newPageView.frame = frame;
[self.scrollView addSubview:newPageView];
[self.pageViews replaceObjectAtIndex:page withObject:newPageView];
}
}
- (void)purgePage:(NSInteger)page {
if (page < 0 || page >= self.pageImages.count) {
// If it's outside the range of what we have to display, then do nothing
return;
}
// Remove a page from the scroll view and reset the container array
UIView *pageView = [self.pageViews objectAtIndex:page];
if ((NSNull*)pageView != [NSNull null]) {
[pageView removeFromSuperview];
[self.pageViews replaceObjectAtIndex:page withObject:[NSNull null]];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *images = _singleRelease[#"images"];
NSMutableArray *mediumImages = [NSMutableArray array];
for (NSDictionary *imageDictionary in images){
NSURL *imageURL = [NSURL URLWithString:imageDictionary[#"image_file"][#"image_file"][#"medium"][#"url"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
[mediumImages addObject:image];
}
self.pageImages = [mediumImages copy];
NSInteger pageCount = self.pageImages.count;
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = pageCount;
self.pageViews = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < pageCount; ++i) {
[self.pageViews addObject:[NSNull null]];
}
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 4
CGSize pagesScrollViewSize = self.scrollView.frame.size;
self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * self.pageImages.count, pagesScrollViewSize.height);
// 5
[self loadVisiblePages];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// Load the pages which are now on screen
[self loadVisiblePages];
}
I tried customizing a code sample I found online, but I cant get it to work with my code.
This is what I have so far:
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *images = _singleRelease[#"images"];
NSMutableArray *mediumImages = [NSMutableArray array];
dispatch_queue_t imageQueue = dispatch_queue_create("Image Queue",NULL);
for (NSDictionary *imageDictionary in images){
dispatch_async(imageQueue, ^{
NSURL *imageURL = [NSURL URLWithString:imageDictionary[#"image_file"][#"image_file"][#"medium"][#"url"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
[mediumImages addObject:image];
dispatch_async(dispatch_get_main_queue(), ^{
NSInteger pageCount = self.pageImages.count;
self.pageImages = [mediumImages copy];
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = pageCount;
self.pageViews = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < pageCount; ++i) {
[self.pageViews addObject:[NSNull null]];
}
});
});
}
}
This was another code sample I tried customizing but I get the same outcome.
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *images = [self.singleRelease[#"images"] copy];
__weak __typeof__(self) weakself = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableArray *mediumImages = [NSMutableArray array];
for (NSDictionary *imageDictionary in images){
NSURL *imageURL = [NSURL URLWithString:imageDictionary[#"image_file"][#"image_file"][#"medium"][#"url"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
if (image) {
[mediumImages addObject:image];
}
}
dispatch_sync(dispatch_get_main_queue(), ^{
if (weakself) {
__typeof__(self) weakself = weakself;
self.pageImages = mediumImages;
NSInteger pageCount = self.pageImages.count;
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = pageCount;
self.pageViews = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < pageCount; ++i) {
[self.pageViews addObject:[NSNull null]];
}
};
});
});
}
Both codes load my Page Control with the correct number of slides, but the images don't appear.
Any help? Thanks.
Fixed it.
Delete viewWillAppear and then replace the current viewDidLoad with this:
/**
* Called after the controller’s view is loaded into memory.
*/
- (void)viewDidLoad
{
[super viewDidLoad];
self.release_name.text = [self.singleRelease objectForKey:#"release_name"];
if ([_singleRelease objectForKey:#"release_price"])
self.release_price.text = [NSString stringWithFormat:#"$%#",[_singleRelease objectForKey:#"release_price"]];
self.release_colorway.text = [self.singleRelease objectForKey:#"release_colorway"];
if([_singleRelease objectForKey:#"release_date"] != NULL)
{
NSString *readableDate = [_singleRelease objectForKey:#"release_date"]; // I assume that this is a string
UpcomingRelease *upcoming = [[UpcomingRelease alloc] init];
upcoming.release_date = readableDate;
self.release_date.text = [NSString stringWithFormat:#"%#", upcoming.formattedDate];
}
NSArray *images = self.singleRelease[#"images"];
// we get the image on a background queue
dispatch_queue_t imageQueue = dispatch_queue_create("Image Queue",NULL);
dispatch_async(imageQueue,
^{
NSMutableArray *mediumImages = [[NSMutableArray alloc] initWithCapacity:images.count];
// for each image url we get the image and add it to the array
for (NSDictionary *imageDictionary in images)
{
NSURL *imageURL = [[NSURL alloc] initWithString:imageDictionary[#"image_file"][#"image_file"][#"medium"][#"url"]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
UIImage *image = [[UIImage alloc] initWithData:imageData];
[mediumImages addObject:image];
}
// once we have obtained all of the images we use them
dispatch_async(dispatch_get_main_queue(),
^{
// we get a strong pointer to the images array and set the pages count according to how many there are
self.pageImages = [mediumImages copy];
NSInteger pageCount = self.pageImages.count;
// we set the page control appropriate for the number of images that need to be presented
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = pageCount;
// we then make mock page views
self.pageViews = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < pageCount; ++i)
{
[self.pageViews addObject:[NSNull null]];
}
// once we have the images we load the pages with them
CGSize pagesScrollViewSize = self.scrollView.frame.size;
self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * self.pageImages.count, pagesScrollViewSize.height);
[self loadVisiblePages];
});
});
_scrollView.showsHorizontalScrollIndicator=NO;
_scrollView.showsVerticalScrollIndicator=NO;
}
The problem was you were trying to load the pages before the images had finished fetching.

Locating markers on the google map

Hello friends i am uploading my code from last few days on the stackoverflow but somwhow i am not getting the thing which i want. Noe once again i am trying this please try to help me out and solve my proplems. Firstly see the code.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
welcomeViewController.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import <UIKit/UIKit.h>
#import <GoogleMaps/GoogleMaps.h>
#interface welcomemapViewController : UIViewController
#property (strong, nonatomic) UITextField *txt;
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
welcomeViewController.m
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import "welcomemapViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kLatestSearchURL [NSURL URLWithString: #"https://maps.googleapis.com/maps/api/place/textsearch/xml?query=Delhi&sensor=true&key=Your API key"]
#interface welcomemapViewController ()
#end
#implementation welcomemapViewController
{
GMSMapView *gmap;
}
#synthesize txt;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
GMSCameraPosition *cam = [GMSCameraPosition cameraWithLatitude:30.7343000 longitude:76.7933000 zoom:12];
gmap = [GMSMapView mapWithFrame:CGRectMake(0, 60, 320, 480) camera:cam];
gmap.myLocationEnabled = YES;
gmap.mapType = kGMSTypeHybrid;
gmap.settings.myLocationButton = YES;
gmap.settings.zoomGestures = YES;
gmap.settings.tiltGestures = NO;
gmap.settings.rotateGestures = YES;
[self.view addSubview:gmap];
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(30.751288, 76.780899);
marker.title = #"Sector -16";
marker.snippet = #"Chandigarh";
marker.map = gmap;
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(200, 65, 100, 40);
[button setTitle:#"SEARCH" forState:UIControlStateNormal];
[button addTarget:self action:#selector(search:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
CGRect frame2 = CGRectMake(10, 68, 200, 30);
txt =[[UITextField alloc]initWithFrame:frame2];
txt.placeholder = #"Search";
txt.userInteractionEnabled = YES;
txt.keyboardType = UIKeyboardTypeAlphabet;
[txt setBorderStyle:UITextBorderStyleRoundedRect];
[self.view addSubview:txt];
// Do any additional setup after loading the view from its nib.
}
-(IBAction)search:(id)sender
{
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=30.7343000,76.7933000&radius=500&types=food&name&sensor=true&key=AIzaSyCGeIN7gCxU8baq3e5eL0DU3_JHeWyKzic"];
//Formulate the string as URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSString *data1 = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"Response data: %#", data1);
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* responseResults = [json objectForKey:#"results"];
NSLog(#"Locations are %#", responseResults);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
now in "NSLog(#"Locations are %#", responseResults);" i am getting my values, i simply want to add these values onto the map in the form of pointers with details.
So kindly help me how it should be done. (And kindly help me with the help of codes)
you can do this by using MKPointAnnotation and then add this MKPointAnnotation in you mapview
CLLocationCoordinate2D annotationCoord;
annotationCoord.latitude = #"your Latitude to point on map";
annotationCoord.longitude = #"your Longitude to point on map";;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = annotationCoord;
annotationPoint.title = #"your title";
annotationPoint.subtitle = #"your subtitle";
[YourmapView addAnnotation:annotationPoint];

Loop add UIImageView Cocoa Touch

having a problem adding multiple ImageViews to my view. I have an array of images and what to cycle through them and add to my view. This snippet adds an image to view, but with no frame!
- (void)cycleImages:(NSArray *)images {
//create an image view
int fromLeft = 5;
int profilesCount = [images count] - 1;
for(int n = 0; n <= profilesCount; n++){
//add image view to view
[self.view addSubview:[[[UIImageView alloc] initWithFrame:CGRectMake(5, fromLeft, 48, 48)] initWithImage:[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[images objectAtIndex:n]]]]]];
fromLeft = fromLeft + 53;
NSLog(#"%d", fromLeft);
}
}
Thanks for your help!
Dex
Its hard to read such code and you have mem leaks. Please, try this.
- (void)cycleImages:(NSArray *)images
{
int fromLeft = 5;
NSURL* url = nil;
UIImage* img = nil;
UIImageView* imgView = nil;
NSData* imgData = nil;
for (NSString* imgURLStr in images)//Using enumeration much more easy and in ObjC style
{
//Put breakpoint here and check all varibles initialized coorecly step by step
url = [NSURL URLWithString:imgURLStr];
imgData = [NSData dataWithContentsOfURL:url];
img = [[UIImage alloc] initWithData:imgData];
imgView = [[UIImageView alloc] initWithImage:img];
imgView.frame = CGRectMake(5, fromLeft, 48, 48);
[self.view addSubView:imgView];
fromLeft = fromLeft + 53;
NSLog(#"%d", fromLeft);
//Clean up
[img release];
[imgView release];
}
}
Thanks!

Resources