Using this link .
i tried to get route direction from one coordinates to another coordinates but didn't get route. Below mention used coding...
NSArray *routesArray = [res objectForKey:#"routes"];
NSDictionary *routeDict = [routesArray objectAtIndex:0];
NSDictionary *routeOverviewPolyline = [routeDict objectForKey:#"overview_polyline"];
NSString *points = [routeOverviewPolyline objectForKey:#"points"];
GMSPath *path = [GMSPath pathFromEncodedPath:points];
polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeColor = [UIColor greenColor];
polyline.strokeWidth = 10.f;
polyline.map = mapView_;
Can anyone know.Help me to solve this issue..
You can use GoogleMapsDirection to get the path or DirectionResponse from the Google Directions API. The NSLogs are useful to see what you are working with.
[[GMDirectionService sharedInstance] getDirectionsFrom:origin to:destination succeeded:^(GMDirection *directionResponse) {
if ([directionResponse statusOK]){
NSLog(#"Duration : %#", [directionResponse durationHumanized]);
NSLog(#"Distance : %#", [directionResponse distanceHumanized]);
NSArray *routes = [[directionResponse directionResponse] objectForKey:#"routes"];
// NSLog(#"Route : %#", [[directionResponse directionResponse] objectForKey:#"routes"]);
}
} failed:^(NSError *error) {
NSLog(#"Can't reach the server")
}];
Once you have the json you can get the path points (this shows the first route at index 0).
GMSPath *path = [GMSPath pathFromEncodedPath:routes[0][#"overview_polyline"][#"points"]];
Then you can convert the path to a polyline and draw it on your mapView and set the strokeColor and strokeWidth if desired.
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeColor = [UIColor redColor];
polyline.strokeWidth = 5.f;
Then set the polyline.map property to your mapView.
polyline.map = mapView;
Finally put it all together
[[GMDirectionService sharedInstance] getDirectionsFrom:origin to:destination succeeded:^(GMDirection *directionResponse) {
if ([directionResponse statusOK]){
NSLog(#"Duration : %#", [directionResponse durationHumanized]);
NSLog(#"Distance : %#", [directionResponse distanceHumanized]);
NSArray *routes = [[directionResponse directionResponse] objectForKey:#"routes"];
// NSLog(#"Route : %#", [[directionResponse directionResponse] objectForKey:#"routes"]);
GMSPath *path = [GMSPath pathFromEncodedPath:routes[0][#"overview_polyline"] [#"points"]];
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeColor = [UIColor redColor];
polyline.strokeWidth = 5.f;
polyline.map = mapView;
}
} failed:^(NSError *error) {
NSLog(#"Can't reach the server")
}];
I find CocoaPods useful for installing the Google Maps SDK and GoogleMapsDirection.
Related
My bar graph disappears when I switch my app to background and then again comes back to foreground.
It's like shown below :
||| || ||
So in the above picture I have gaps, that means when my app is in background core plot does not draw bar graph. Is it a limitation of core plot?
My main task is to draw one bar per second and I have done this, but it's not working while in background. Is there some other alternate option by which I can achieve this?
Here is what I tried:
I made my graph object nil and then tried it reloading when app again comes back to foreground. But it didn't work.
-(void)redrawGraphWhenApplicationEntersForeground
{
NSLog(#"reload graph");
NSLog(#"all plots : %# , %#", [self.graph allPlots], plotArray);
DDLogInfo(#"relaod graph when entered in Foreground ");
// [self.data removeAllObjects];
//Create graph and set it as host view's graph
self.graph = nil;
[self.graph reloadDataIfNeeded];
}`
Here is my full code :
// Update is called by a timer ( of 10 second) , so that each second this method will be called and it will draw a bar.
- (void)update:(id)data1 withState:(NSInteger) type
{
switch (type) {
case ZAP_UPDATE:
if(curLinkType == DOWNLINK)
{
[self drawDownlinkGrpah];
}else if(curLinkType == UPLINK)
{
[self drawUplinkGrpah];
}
[gauge setValue:speedValue];
break;
case ZAP_DONE:
[self displayDone:type speedBps:speedBps pktLoss:pktLoss srcdst:[zap destinationAddress]];
onTap = false;
runningTime=0;
if(gauge != nil){
[gauge setValue:0];
}
{
NSArray *parameter = [NSArray arrayWithObjects: speed, unit, nil];
[self performSelector:#selector(stopGauge:) withObject:parameter afterDelay:0.2];
}
}
}
- (void)drawDownlinkGrpah {
DownlinCount++;
self.downlinkdata = [NSMutableArray array];
double position = DownlinCount*((4*10)/(double)durationval);
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:speedBarValue],BAR_HEIGHT,
[UIColor orangeColor],COLOR,
nil];
[self.downlinkdata addObject:bar];
self.data = self.downlinkdata;
[self generateBarPlotForDownlink:YES];
}
- (void)drawUplinkGrpah {
UplinkCount++;
self.uplinkdata = [NSMutableArray array];
double position = UplinkCount*((4*10)/(double)durationval);
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:speedBarValue],BAR_HEIGHT,
[UIColor orangeColor],COLOR,
nil];
[self.uplinkdata addObject:bar];
self.data = self.uplinkdata;
[self generateBarPlotForDownlink:NO];
}
- (NSInteger)getBarposition:(NSInteger)samplesize {
return (4*10)/samplesize;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)resetGraph:(UIImageView*) imageview {
for(UIView *view in imageview.subviews)
[view removeFromSuperview];
[imageview setImage:[UIImage imageNamed:#"graph_container"]];
}
#pragma mark -
-(void)appGoesinBackground
{
// NSLog(#"make nil graph");
// DDLogInfo(#"remove graph when entered in background ");
//
self.graph = nil;
// [self.data removeAllObjects];
[plotArray removeAllObjects]; // remove all data before entering to background
[[NSNotificationCenter defaultCenter] addObserver: self
selector: #selector(redrawGraphWhenApplicationEntersForeground)
name: UIApplicationDidBecomeActiveNotification
object: nil];
}
// redraw graph ..
-(void)redrawGraphWhenApplicationEntersForeground
{
NSLog(#"reload graph");
NSLog(#"all plots : %# , %#", [self.graph allPlots], plotArray);
DDLogInfo(#"relaod graph when entered in Foreground ");
// [self.data removeAllObjects];
//Create graph and set it as host view's graph
// self.graph = nil;
//
for (CPTBarPlot *p in plotArray) {
// [self.graph addPlot:p];
[p reloadData];
}
}
#pragma mark - generate bar plot
- (void)generateBarPlotForDownlink:(BOOL)enabled
{
NSLog(#"generateBarPlotForDownlink >>>>>>");
//Create host view
self.hostingView = [[CPTGraphHostingView alloc] initWithFrame:CGRectMake(-35, -20, 128, 73)];
//Create graph and set it as host view's graph
self.graph = [[CPTXYGraph alloc] initWithFrame:self.downlinkImageView.frame];
self.graph.plotAreaFrame.masksToBorder = NO;
[self.hostingView setHostedGraph:self.graph];
if(enabled) // for downlink graph ..
{
self.downlinkImageView.image=nil;
[self.downlinkImageView addSubview:self.hostingView];
}
else{ // for uplink graph ..
self.uplinkImageView.image=nil;
[self.uplinkImageView addSubview:self.hostingView];
}
// Create bar plot and add it to the graph
CPTBarPlot *plot = [[CPTBarPlot alloc] init] ;
plot.dataSource = self;
plot.delegate = self;
//set axes ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat((AXIS_END - AXIS_START)+1)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat(maxYRange)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
axisSet.xAxis.majorIntervalLength = CPTDecimalFromFloat(1.0f);
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(1.0f);
axisSet.xAxis.minorTickLength = 1.0f;
axisSet.yAxis.minorTickLength = 1.0f;
axisSet.hidden=YES;
axisSet.xAxis.labelingPolicy=CPTAxisLabelingPolicyNone;
axisSet.yAxis.labelingPolicy=CPTAxisLabelingPolicyNone;
float barwidht = (2*10.0)/(float)durationval;
NSString *inStr = [NSString stringWithFormat: #"%f", barwidht];
plot.barWidth = [[NSDecimalNumber decimalNumberWithString:inStr] // Need to change according sample // 1.5 for 10 , 0.75 for 20
decimalValue];
plot.barOffset = [[NSDecimalNumber decimalNumberWithString:#"5.0"]
decimalValue];
plot.barCornerRadius = 0.0;
// Remove bar outlines
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor clearColor];
plot.lineStyle = borderLineStyle;
plot.identifier = #"chocoplot";
[self.graph addPlot:plot];
// Add plot to array in case if app is moved to background state ..
[plotArray addObject:plot];
NSLog(#"plot : %#",plot);
NSLog(#"plot added ..%lu", (unsigned long)plotArray.count );
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [plot.identifier isEqual:#"chocoplot"] )
return [self.data count];
return 0;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
if(fieldEnum == CPTBarPlotFieldBarLocation)
return [bar valueForKey:BAR_POSITION];
else if(fieldEnum ==CPTBarPlotFieldBarTip)
return [bar valueForKey:BAR_HEIGHT];
}
return [NSNumber numberWithFloat:0];
}
-(CPTFill *)barFillForBarPlot:(CPTBarPlot *)barPlot
recordIndex:(NSUInteger)index
{
if ( [barPlot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
CPTGradient *gradient = [CPTGradient gradientWithBeginningColor:[CPTColor redColor]
endingColor:[bar valueForKey:#"COLOR"]
beginningPosition:0.0 endingPosition:0.6 ];
[gradient setGradientType:CPTGradientTypeAxial];
[gradient setAngle:320.0];
CPTFill *fill = [CPTFill fillWithGradient:gradient];
return fill;
}
return [CPTFill fillWithColor:[CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
}
Screenshot:
You don't need to create a new graph every time you get new plot data. Just add the new point to the data array and call -reloadData on the plot.
When the app goes into the background, just clear your data array and call -reloadData on the plot. It will reload the empty data and display the graph when the app comes back to the foreground. There's no reason to set self.graph to nil unless you remove the graph from the hosting view and you want it to go away. From what I can see in the posted code, the graph is still in the hosting view, but you've lost your reference to it, making any updates you make when the app comes to the foreground ineffective.
Here is the code that worked for me :
- (void)drawDownlinkGrpah {
NSLog(#"drawDownlinkGrpah CAlled");
DownlinCount++;
double position = DownlinCount*((4*10)/(double)durationval);
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:speedBarValue],BAR_HEIGHT,
[UIColor orangeColor],COLOR,
nil];
[self.downlinkdata addObject:bar];
self.data = self.downlinkdata;
[self generateBarPlotForDownlink:YES];
}
#pragma mark - generate bar
- (void)generateBarPlotForDownlink:(BOOL)enabled
{
if(enabled)
{
self.downlinkImageView.image=nil;
if(![self.hostingView isDescendantOfView:self.downlinkImageView])
{
// Configure hosting view so that it appears from fresh ..
[self configureGraph];
[self.downlinkImageView addSubview:self.hostingView];
NSLog(#"hosting view added in downlink view ");
}
}
else
{
self.uplinkImageView.image=nil;
// if hosting view is not in uplink view
if(![self.hostingView isDescendantOfView:self.uplinkImageView])
{
// Configure hosting view so that it appears from fresh ..
[self configureGraph];
[self.uplinkImageView addSubview:self.hostingView];
NSLog(#"hosting view added in uplink view ");
}
}
//set axes ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat((AXIS_END - AXIS_START)+1)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat(maxYRange)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
axisSet.xAxis.majorIntervalLength = CPTDecimalFromFloat(1.0f);
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(1.0f);
axisSet.xAxis.minorTickLength = 1.0f;
axisSet.yAxis.minorTickLength = 1.0f;
axisSet.hidden=YES;
axisSet.xAxis.labelingPolicy=CPTAxisLabelingPolicyNone;
axisSet.yAxis.labelingPolicy=CPTAxisLabelingPolicyNone;
// Create bar plot and add it to the graph
NSLog(#"plot created %ld", (long)durationval);
CPTBarPlot *plot = [[CPTBarPlot alloc] init] ;
plot.dataSource = self;
plot.delegate = self;
float barwidht = (2*10.0)/(float)durationval;
NSString *inStr = [NSString stringWithFormat: #"%f", barwidht]; //CPTDecimalFromDouble(2.0);
plot.barWidth = [[NSDecimalNumber decimalNumberWithString:inStr]
decimalValue];// Need to change according sample // 1.5 for 10 , 0.75 for 20
plot.barWidth = CPTDecimalFromDouble(barwidht);
plot.barOffset = [[NSDecimalNumber decimalNumberWithString:#"5.0"]
decimalValue];
plot.barCornerRadius = 0.0;
// Remove bar outlines
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor clearColor];
plot.lineStyle = borderLineStyle;
plot.identifier = #"chocoplot";
[self.graph addPlot:plot];
}
#pragma mark - core plot data source and delegate methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [plot.identifier isEqual:#"chocoplot"] )
return [self.data count];
return 0;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
if(fieldEnum == CPTScatterPlotFieldX)
return [bar valueForKey:BAR_POSITION];
else if(fieldEnum ==CPTScatterPlotFieldY)
return [bar valueForKey:BAR_HEIGHT];
}
return [NSNumber numberWithFloat:0];
}
drawDownlinkGraph method would be called each second using a timer and it will call generateBarPlotForDownlink: Method every second . And bar will be drawn each second on a real time basis even if APP is in background.
I`ve created similar code as was shown on WWDC for displaying pin on snapshots, but pin image is not displayed:
MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init];
options.region = self.mapView.region;
options.scale = 2;
options.size = self.mapView.frame.size;
MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
[snapshotter startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error)
{
MKAnnotationView *pin = [[MKAnnotationView alloc] initWithAnnotation:nil reuseIdentifier:#""];
UIImage *image;
UIImage *finalImage;
image = snapshot.image;
NSLog(#"%f", image.size.height);
UIImage *pinImage = pin.image;
CGPoint pinPoint = [snapshot pointForCoordinate:CLLocationCoordinate2DMake(self.longtitude, self.latitude)];
CGPoint pinCenterOffset = pin.centerOffset;
pinPoint.x -= pin.bounds.size.width / 2.0;
pinPoint.y -= pin.bounds.size.height / 2.0;
pinPoint.x += pinCenterOffset.x;
pinPoint.y += pinCenterOffset.y;
UIGraphicsBeginImageContextWithOptions(image.size, YES, image.scale);
[image drawAtPoint:CGPointMake(0, 0)];
[pinImage drawAtPoint:pinPoint];
finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImageJPEGRepresentation(finalImage, 0.95f);
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [pathArray objectAtIndex:0];
NSLog(#"%#", path);
NSString *fileWithPath = [path stringByAppendingPathComponent:#"test.jpeg"];
[data writeToFile:fileWithPath atomically:YES];
}];
Only snapshot of map is displayed without pin image.
If you're expecting the default pin image to appear, you need to create an MKPinAnnotationView instead of the plain MKAnnotationView (which has no default image -- it's blank by default).
Also, please note that the latitude and longitude parameters are backwards in this line:
CGPoint pinPoint = [snapshot pointForCoordinate:CLLocationCoordinate2DMake(
self.longtitude, self.latitude)];
In CLLocationCoordinate2DMake, latitude should be the first parameter and longitude the second.
I Have something like that:
for(MKMapItem *mapItem in response.mapItems){
MKPlacemark *placeMark = mapItem.placemark;
NSLog(#"showSearchResponse: mapItem = %# coordinate = %g,%g \nname = %#\naddressDictionary = %#",
mapItem,
placeMark.coordinate.latitude,
placeMark.coordinate.longitude,
mapItem.name,
placeMark.addressDictionary);
[self.mapView addAnnotation:placeMark];
scrollText.editable=NO;
scrollText.scrollEnabled = YES;
scrollText.text = [NSString stringWithFormat:#"%#",placeMark.addressDictionary];
i want to list all the results in TextView, this code showed me only last result
Thx for help !
The problem is at the end of your loop:
scrollText.text = [NSString stringWithFormat:#"%#",placeMark.addressDictionary];
You are resetting the text to the last entry.
So you have two options. Once of them is just concatenate a string with your results and set that as the text for your scrollText or concatenate the string over scrolText like this
scrollText.text = [NSString stringWithFormat:#"%#%#",scrollText.text, placeMark.addressDictionary];
You are re-setting value of scrollText each time. So try this one:
NSMutableString *resultString = [[NSMutableString alloc]init];
for(MKMapItem *mapItem in response.mapItems){
MKPlacemark *placeMark = mapItem.placemark;
NSLog(#"showSearchResponse: mapItem = %# coordinate = %g,%g \nname = %#\naddressDictionary = %#",
mapItem,
placeMark.coordinate.latitude,
placeMark.coordinate.longitude,
mapItem.name,
placeMark.addressDictionary);
[self.mapView addAnnotation:placeMark];
[resultString appendFormate:#"%#\n",placeMark.addressDictionary];
}
scrollText.editable=NO;
scrollText.scrollEnabled = YES;
scrollText.text = resultString;
I hope this will be useful.
I am trying to add elements to a scroll view using this code:
int missionCount;
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
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];
missionsScroll.contentSize = CGSizeMake(768, 1005);
id value;
int badgeY1;
int badgeY2;
int badgeY3;
badgeY1 = 146;
badgeY2 = 188;
badgeY3 = 188;
while((value = [inner nextObject])) {
NSLog(#"value is: %#", value);
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 *inner2 = [moreData objectEnumerator];
id value2;
int badgeX;
int badgeCount;
badgeX = 0;
badgeCount = 0;
while((value2 = [inner2 nextObject])) {
UIProgressView *progressView;
progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(323, badgeY1, 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(66, badgeY1, 227, 21)];
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];
UILabel *requirementsLabel;
requirementsLabel = [[UILabel alloc] initWithFrame:CGRectMake(66, badgeY2+25, 227, 21)];
requirementsLabel.backgroundColor = [UIColor clearColor];
requirementsLabel.textColor = [UIColor whiteColor];
requirementsLabel.font = [UIFont fontWithName:#"Papyrus" size:19];
requirementsLabel.text = #"To complete you need:";
[missionsScroll addSubview:requirementsLabel];
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, badgeY2+70, 70, 70)];
[missionsScroll addSubview:badge];
[badge release];
badgeCount = badgeCount+1;
NSLog(#"badgeCount is: %i", badgeCount);
if (badgeCount == 4) {
NSLog(#"Badge Count = 4");
badgeY2 = badgeY2 +70;
badgeX = 0;
badgeCount = 0;
} else {
NSLog(#"Badge Count ≠ 4");
badgeX = badgeX +75;
}
}
NSLog(#"1st While loop done");
// 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 +200;
badgeY2 = badgeY2 +200;
badgeY3 = badgeY3 +200;
missionCount = missionCount+1;
}
NSLog(#"While loops done");
for (int a; missionCount > 4; a = a+1) {
missionsScroll.contentSize = CGSizeMake(776, missionsScroll.contentSize.height+200);
}
Nothing is showing up in the scroll view.
It's not obvious what is happening, but first things to check are where the views are valid (not nil) and that this code is running on the main thread.
Put these in and post the results.
NSLog(#"missionsScroll: %#", (missionsScroll==nil)?#"NIL":#"OK");
NSLog(#"progressView: %#", (progressView==nil)?#"NIL":#"OK");
NSLog(#"missionName: %#", (missionName==nil)?#"NIL":#"OK");
NSLog(#"mainThread: %#", ([NSThread isMainThread])?#"OK":#"Background Thread");
Your code is quite convoluted and very difficult to read. Perhaps you could check if your complicated coordinates calculations work as expected, e.g.
NSLog(#"Frame of badge %#", NSStringFromCGRect(badge.frame));
How many times are your while loops iterating? The outer loop increases the y-position of your labels. But the labels will only be displayed at the end of the run loop / start of the next run loop. If you exit this method with the labels with a high y-value then you'll not see them. (It doesn't matter how many times you change the y-value while you're running this code. The display will only update when it's all done.)
** Correction ** You seem to be adding new views each time around your while loop. So in fact I'd expect you to have multiple copies of the subviews appearing when they finally get displayed.
(There's a lot of code to wade through here. If my answer is way off, you might get better answers, but trimming back some of the code and isolating the issue.)
I have a working core-plot, my first one and am currently trying to implement annotation. I have logged the annotation, and the x and y coordinates and they are null. thanks
-(void)scatterPlot:(CPTScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index
{
//CPTGraph* graph = [graphs objectAtIndex:0];
NSLog(#"add annotation called");
if ( symbolTextAnnotation ) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
//[graph removeAnnotation:symbolTextAnnotation];
symbolTextAnnotation = nil;
}
// Setup a style for the annotation
CPTMutableTextStyle *hitAnnotationTextStyle = [CPTMutableTextStyle textStyle];
hitAnnotationTextStyle.color = [CPTColor whiteColor];
hitAnnotationTextStyle.fontSize = 16.0f;
hitAnnotationTextStyle.fontName = #"Helvetica-Bold";
// Determine point of symbol in plot coordinates
NSNumber *x = [[plotData objectAtIndex:index] valueForKey:#"x"];
NSNumber *y = [[plotData objectAtIndex:index] valueForKey:#"y"];
NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
NSLog(#"x %#, y %#",[[plotData objectAtIndex:index] valueForKey:#"x"],y);
// Add annotation
// First make a string for the y value
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setMaximumFractionDigits:2];
NSString *yString = [formatter stringFromNumber:y];
// Now add the annotation to the plot area
CPTTextLayer *textLayer = [[[CPTTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle] autorelease];
symbolTextAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:graph.defaultPlotSpace anchorPlotPoint:anchorPoint];
symbolTextAnnotation.contentLayer = textLayer;
symbolTextAnnotation.displacement = CGPointMake(0.0f, 20.0f);
[graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];
//[graph addAnnotation:symbolTextAnnotation];
CPTAnnotation *annot = [graph.plotAreaFrame.plotArea.annotations objectAtIndex:0];
NSLog(#"annot: %#", annot);
}
This is the code that determines the anchor point:
NSNumber *x = [[plotData objectAtIndex:index] valueForKey:#"x"];
NSNumber *y = [[plotData objectAtIndex:index] valueForKey:#"y"];
NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
It assumes your plot data is stored as NSNumber objects in an array of dictionaries with "x" and "y" keys. If your data is stored some other way, you'll have to extract the values differently. The important thing is to package the two numbers in an NSArray with the x-value first and the y-value second.