I want to show to location name and the pin point in my mapView.I Tried many ways but none of them help me. And I am stuck at this position.
i am using this piece of code:
-(void)getMe:(id)sender
{
[self.view endEditing:YES];
NSString *addresss = userText.text;
NSString *esc_addr = [addresss stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat: #"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:req]];
NSDictionary *googleResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *resultsDict = [googleResponse valueForKey: #"results"]; // get the results dictionary
NSDictionary *geometryDict = [ resultsDict valueForKey: #"geometry"]; // geometry dictionary within the results dictionary
NSDictionary *locationDict = [ geometryDict valueForKey: #"location"]; // location dictionary within the geometry dictionary
// nslo (#”– returning latitude & longitude from google –”);
NSArray *latArray = [locationDict valueForKey: #"lat"]; NSString *latString = [latArray lastObject]; // (one element) array entries provided by the json parser
NSArray *lngArray = [locationDict valueForKey: #"lng"]; NSString *lngString = [lngArray lastObject]; // (one element) array entries provided by the json parser
myLocation.latitude = [latString doubleValue]; // the json parser uses NSArrays which don’t support “doubleValue”
myLocation.longitude = [lngString doubleValue];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = myLocation.latitude;
zoomLocation.longitude=myLocation.longitude;
// 2
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*1500, 0.5*1500);
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
CLLocationCoordinate2D coordinates;
coordinates.latitude = myLocation.latitude;
coordinates.longitude=myLocation.longitude;
point.coordinate =coordinates;
point.title = #"My Location";
point.subtitle = #"Reached";
[mp addAnnotation:point];
// 3
[mp setRegion:viewRegion animated:YES];
}
mp is my mapView Outlet.I am geting this output:
But I want location title with pin. What can i do to achieve this.
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
// Add an annotation
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate;
point.title = #"Where am I?";
point.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:point];
}
Related
Is there anyone that can help me combine this
https://github.com/AndreyLunevich/DLImageLoader-iOS
With my code below... I am not understanding as my images are loaded from an NSString in core data and not a URL (maybe I cannot use this helper file)
My code is:
SCTableViewSection *Section3 = [self.tableViewModel sectionAtIndex:0];
Section3.cellActions.lazyLoad = ^(SCTableViewCell *cell, NSIndexPath *indexPath)
{
DLImageView *imageView = (DLImageView *)[cell viewWithTag:1];
NSString *imageString = (NSString *)[cell.boundObject valueForKey:#"thumbnail"];
NSString *fullName = [NSString stringWithFormat:#"Documents/%#", imageString];
NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:fullName];
UIImage *originalImage = [UIImage imageWithContentsOfFile:imagePath];
NSLog(#"added image from lazyload");
// size of actual thumbnail to display in cell
CGSize destinationSize = CGSizeMake(154,95); // size of actual thumbnail
UIGraphicsBeginImageContext(destinationSize);
[originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[UIView transitionWithView:imageView
duration:2.25f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
imageView.image = thumbnail;
} completion:nil];
};
I am creating an app that pulls data from a server and pinpoints the different houses on a map. My problem is that it does display the annotations but when I click on them they do not respond
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
I put my annotations in an array by:
int s;
self.mapAnnotations = [[NSMutableArray alloc] init];
for(s=0; s < numberOfAnnotations; s++)
{
//NSDictionary *dict2 = [parser objectWithString:[[arrayOfResults objectAtIndex:0] description]];
CLLocationDegrees daLong = [[[[[arrayOfResults objectAtIndex:s] objectForKey:#"map"] objectForKey:#"longitude"] description] floatValue];
CLLocationDegrees daLat = [[[[[arrayOfResults objectAtIndex:s] objectForKey:#"map"] objectForKey:#"latitude"] description] floatValue];
/*self.customAnnotation = [[BasicMapAnnotation alloc] initWithLatitude:daLat andLongitude:daLong];
[self.mapView addAnnotation:self.customAnnotation];*/
BasicMapAnnotation *m = [[BasicMapAnnotation alloc] initWithLatitude:daLat andLongitude:daLong];
[self.mapAnnotations addObject:m];
}
[self.mapView addAnnotations:self.mapAnnotations];
NSLog(#"this number of annotations %d", [self.mapAnnotations count]);
I also noticed when I created a separate house to place on the map in my viewDidLoad:
self.normalAnnotation = [[BasicMapAnnotation alloc] initWithLatitude:38 andLongitude:-90.2045];
self.normalAnnotation.title = #" ";
[self.mapView addAnnotation:self.normalAnnotation];
It did work when I clicked on it, but the ones passed through the array didn't work.
Can anyone help me figure out why it's not responding?
That's because annotations should have a title for them to display a callout. In your for loop, set the title property like you did with self.normalAnnotation.title = #" ".
I tried to write simple demo to capture a video with audio from iphone(like a in game recorder). After searching for some solutions I came up with the follow stuffs:
-(void) startScreenRecording
{
NSLog(#"start screen recording");
// create the AVAssetWriter
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *moviePath = [documentPath stringByAppendingPathComponent: #"/video.mov"];
NSLog(#"moviePath:%#", moviePath);
if ([[NSFileManager defaultManager] fileExistsAtPath:moviePath])
{
[[NSFileManager defaultManager] removeItemAtPath:moviePath error:nil];
}
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
NSError *movieError = nil;
[assetWriter release];
assetWriter = [[AVAssetWriter alloc] initWithURL:movieURL
fileType: AVFileTypeQuickTimeMovie
error: &movieError];
NSDictionary *assetWriterInputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecH264, AVVideoCodecKey,
[NSNumber numberWithInt:FRAME_WIDTH], AVVideoWidthKey,
[NSNumber numberWithInt:FRAME_HEIGHT], AVVideoHeightKey,
nil];
assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType: AVMediaTypeVideo
outputSettings:assetWriterInputSettings];
assetWriterInput.expectsMediaDataInRealTime = YES;
[assetWriter addInput:assetWriterInput];
[assetWriterPixelBufferAdaptor release];
assetWriterPixelBufferAdaptor = [[AVAssetWriterInputPixelBufferAdaptor alloc]
initWithAssetWriterInput:assetWriterInput
sourcePixelBufferAttributes:nil];
[assetWriter startWriting];
firstFrameWallClockTime = CFAbsoluteTimeGetCurrent();
[assetWriter startSessionAtSourceTime: CMTimeMake(0, TIME_SCALE)];
// start writing samples to it
[assetWriterTimer release];
assetWriterTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:#selector (writeSample:)
userInfo:nil
repeats:YES];
}
-(void) writeSample: (NSTimer*) _timer
{
if (assetWriterInput.readyForMoreMediaData)
{
CVReturn cvErr = kCVReturnSuccess;
// get screenshot image!
CGImageRef image = (CGImageRef) [[self createARGBImageFromRGBAImage:[AWScreenshot takeAsImage]] CGImage];
// prepare the pixel buffer
CVPixelBufferRef pixelBuffer = NULL;
CFDataRef imageData= CGDataProviderCopyData(CGImageGetDataProvider(image));
cvErr = CVPixelBufferCreateWithBytes(kCFAllocatorDefault,
FRAME_WIDTH,
FRAME_HEIGHT,
kCVPixelFormatType_32ARGB,
(void*)CFDataGetBytePtr(imageData),
CGImageGetBytesPerRow(image),
NULL,
NULL,
NULL,
&pixelBuffer);
// calculate the time
CFAbsoluteTime thisFrameWallClockTime = CFAbsoluteTimeGetCurrent();
CFTimeInterval elapsedTime = thisFrameWallClockTime - firstFrameWallClockTime;
//NSLog (#"elapsedTime: %f", elapsedTime);
CMTime presentationTime = CMTimeMake (elapsedTime * TIME_SCALE, TIME_SCALE);
// write the sample
BOOL appended = [assetWriterPixelBufferAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:presentationTime];
if (appended)
{
NSLog (#"appended sample at time %lf", CMTimeGetSeconds(presentationTime));
}
else
{
NSLog (#"failed to append");
[self stopScreenRecording];
}
}
}
And the video(.mov) file is generated successfully...
But, now I'd like to capture the audio from the iphone(say some sound effect and bg music while playing a game) along with the video...
I searched the net and all I got is solutions about "how to merge a already-exist sound file with a already-exist movie"...
Do I have to record the audio and video separately and then merge it after recording? Is there a way to capture them together ?
Any suggestion would be much appreciated, thanks :)
I am trying to change the desktop image; the procedure I've come up with is below. The first time this code is run, the resized image is displayed on screen as wallpaper, but the next time there is no reaction. What am I doing wrong?
-(IBAction)click:(id)sender
{
NSData *sourceData;
NSError *error;
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
screenArray = [NSScreen screens];
screenCount = [screenArray count];
unsigned index = 0;
for (index; index < screenCount; index++)
{
screenz = [screenArray objectAtIndex: index];
screenRect = [screenz visibleFrame];
}
NSLog(#"%fx%f",screenRect.size.width, screenRect.size.height);
arrCatDetails = [strCatDetails componentsSeparatedByString:appDelegate.strColDelimiter];
NSString *imageURL = [NSString stringWithFormat:#"upload/product/image/%#_%#_%d.jpg",[arrCatDetails objectAtIndex:0],appDelegate.str104by157Name,iSelectedImgIndex];
NSString *ima = [imageURL lastPathComponent];
NSString *str = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *dataFilePath = [str stringByAppendingPathComponent:ima];
NSString *imagePath = [NSString stringWithFormat:#"file://localhost%#",dataFilePath];
NSURL *url = [[NSURL alloc] init];
url = [NSURL URLWithString:imagePath];
sourceData = [NSData dataWithContentsOfURL:url];
sourceImage = [[NSImage alloc] initWithData: sourceData];
resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(screenRect.size.width, screenRect.size.height)];
NSSize originalSize = [sourceImage size];
[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, screenRect.size.width, screenRect.size.height) fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];
NSData *resizedData = [resizedImage TIFFRepresentation];
NSBitmapImageRep* theImageRepresentation = [NSBitmapImageRep imageRepWithData:resizedData];
newimage = #"editwall.jpg";
newFilePath = [str stringByAppendingPathComponent:newimage];
NSData* theImageData = [theImageRepresentation representationUsingType:NSJPEGFileType properties:nil];
[theImageData writeToFile: newFilePath atomically: YES];
if([filemgr fileExistsAtPath:newFilePath] == YES)
{
imagePath1 = [NSString stringWithFormat:#"file://localhost%#",newFilePath];
urlz = [NSURL URLWithString:imagePath1];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:nil, NSWorkspaceDesktopImageFillColorKey, [NSNumber numberWithBool:NO], NSWorkspaceDesktopImageAllowClippingKey, [NSNumber numberWithInteger:NSImageScaleProportionallyUpOrDown], NSWorkspaceDesktopImageScalingKey, nil];
[[NSWorkspace sharedWorkspace] setDesktopImageURL:urlz forScreen:[[NSScreen screens] lastObject] options:options error:&error];
}
else
{
NSLog(#"No");
}
[sourceImage release];
[resizedImage release];
}
Why not try -[NSWorkspace setDesktopImageURL:forScreen:options:error:]? Apple has a sample project called DesktopImage to give you some idea how to use it.
Edit (after reading your code more carefully):
The problem you're having may be because of your call to +[NSDictionary dictionaryWithObjectsAndKeys:] See the nil at the end of the list of arguments? That's how you tell NSDictionary that your argument list is done. You can't put nil in the list, because it will stop reading the list at that point. If you want to specify a key that has no value, you have to use [NSNull null].
An aside: you've got a memory management issue in your code:
// allocates memory for an NSURL
NSURL * url = [[NSURL alloc] init];
// allocates more memory for an NSURL, and leaks
// the earlier allocation
url = [NSURL URLWithString:imagePath];
Just do one or the other:
// If you do it this way, you will have to call
// [url release] later
NSURL * url = [[NSURL alloc] initWithString:imagePath];
// This memory will be released automatically
NSURL * otherUrl = [NSURL URLWithString:imagePath];
Almost sorted with my 1st app, just a simple news app but when I load it onto my iPhone the scroll seems jerky can someone have a look at my function and see if i'm doing something wrong.
I need the image on the right hand side thats why i'm using custom cells.
Thanks
For any help
#define DATELABEL_TAG 1 #define MAINLABEL_TAG 2 #define PHOTO_TAG 3
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MainNewsCellIdentifier = #"MainNewsCellIdentifier";
UILabel *mainLabel, *dateLabel;
UIImageView *photo;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: MainNewsCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: MainNewsCellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
dateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(15.0,15.0,170.0,15.0)] autorelease];
dateLabel.tag = DATELABEL_TAG;
dateLabel.font = [UIFont systemFontOfSize:10.0];
dateLabel.textAlignment = UITextAlignmentLeft;
dateLabel.textColor = [UIColor darkGrayColor];
dateLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin; //| UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:dateLabel];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(15.0,28.0,170.0,60.0)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont boldSystemFontOfSize:14.0];
mainLabel.textColor = [UIColor blackColor];
mainLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
mainLabel.numberOfLines = 0;
//mainLabel.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:mainLabel];
photo = [[[UIImageView alloc] initWithFrame:CGRectMake(190.0,15.0,85.0,85.0)] autorelease];
photo.tag = PHOTO_TAG;
photo.contentMode = UIViewContentModeScaleAspectFit;//UIViewContentModeScaleAspectFit; //
[cell.contentView addSubview:photo];
}
else {
dateLabel = (UILabel *)[cell.contentView viewWithTag:DATELABEL_TAG];
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
photo = (UIImageView *)[cell.contentView viewWithTag:PHOTO_TAG];
}
NSUInteger row = [indexPath row];
NSDictionary *stream = (NSDictionary *) [dataList objectAtIndex:row];
NSString *title = [stream valueForKey:#"title"];
NSString *titleString = #"";
if( ! [title isKindOfClass:[NSString class]] )
{
titleString = #"";
}
else
{
titleString = title;
}
CGSize maximumSize = CGSizeMake(180, 9999);
UIFont *dateFont = [UIFont fontWithName:#"Helvetica" size:14];
CGSize dateStringSize = [titleString sizeWithFont:dateFont
constrainedToSize:maximumSize
lineBreakMode:mainLabel.lineBreakMode];
CGRect dateFrame = CGRectMake(15.0, 28.0, 170.0, dateStringSize.height);
mainLabel.frame = dateFrame;
mainLabel.text = titleString;
dateLabel.text = [stream valueForKey:#"created"];
NSString *i = [NSString stringWithFormat:#"http://www.website.co.uk/images/%#", [stream valueForKey:#"image"]];
NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:i]];
UIImage *newsImage = [[UIImage alloc] initWithData:imageURL];
photo.image = newsImage;
[imageURL release];
[newsImage release];
return cell;
}
The problem is this:
NSString *i = [NSString stringWithFormat:#"http://www.website.co.uk/images/%#", [stream valueForKey:#"image"]];
NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:i]];
UIImage *newsImage = [[UIImage alloc] initWithData:imageURL];
You effectively say here, that as soon as the cell needs to be displayed, the image must be fetched and presented. This will cost some time - too much for a good user experience.
You should fetch the images before or while you present the table view, and cache them, e.g. in an array. Or you must handle things asynchronously, meaning that you do the loading in the background, and not wait with return cell; until the image is actually downloaded. This will be a little harder to get right.
Even if you asynchronously download images, you'll still have a jerky scroll.
Why? It's lazy image decompression. ios performs decompression at the moment it will be displayed on the screen. You have to manually decompress the images in a background thread.
Decompression does not merely mean instantiating a UIImage object. It can be somewhat complicated. The best solution, is to download SDWebImage and use the image decompressor that's included. SDWebImage will asynchronously download and perform decompression for you.
To read more about the issue see: http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/