NSXML Parsing with Rest api and Mapview with Annotation?


Hi,

Today I am going to explain you How to perform Parsing with NSXML and How to show annotation in MKMapView.

Here I am Taking 1 UITextField and 1 UIButton.Whatever city name you will enter in the Textfield and Press Button it will show you in MKMapView with Annotation.

Step 1: Add Frameworks

1.CoreLocation

2.MapKit

step 2: Add Files

1.Place.h and Place.m

2.PlaceMark.h and PlaceMark.m (I will Provide).

step 3: Import Files in your view controller’s header file  and Declare Variables as shown in the Screenshots.

step 4: @synthesize all Variables as shown.

Step 5: Take NSString with Rest api and provide the textfield value to it.Make the connection with URL Request as shown.

NSString *strUrl = [NSString stringWithFormat:@”http://maps.googleapis.com/maps/api/geocode/xml?address=%@&sensor=false”,self.txtSearch.text];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:strUrl]] delegate:self];

check the connection object

if(conn)
self.data = [[NSMutableData data] init];

Step 6:Implement all the connection Methods as shown.

#pragma mark – Connection Delegates Methods

– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@”Error ==>%@”,error);

}
– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

}

– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.data appendData:data];

}
– (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//Standard NSXMLParser – SAX Parser
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:self.data];
parser.delegate=self;
[parser parse];
}
Step 7:Now Implement Parsing Methods with Root Tag and Object Tag so it will give’s you all the tags.

#pragma mark – NSXML Parsing Delegates Methods

// Document handling methods
// sent when the parser begins parsing of the document.
– (void)parserDidStartDocument:(NSXMLParser *)parser{

}
// sent when the parser finds an element start tag.
– (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if([elementName isEqualToString:@”GeocodeResponse“])
self.arrResult = [NSMutableArray array];
else if ([elementName isEqualToString:@”result“])
self.dMain = [NSMutableDictionary dictionary];
}
– (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
self.strings=string;
}

// sent when an end tag is encountered. The various parameters are supplied as above.
// sent when the parser has completed parsing. If this is encountered, the parse was successful.
– (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:@”GeocodeResponse“]){

}else if ([elementName isEqualToString:@”result“])
{
[self.arrResult addObject:self.dMain];
self.dMain=nil;
}else {
[self.dMain setObject:self.strings forKey:elementName];
}
}

Step 7:In parserDidEndDocument method you will get all the value whatever you required.Here I am getting Latitude/Longitude and Address as shown.

=> Make the object of Place class and Provide the parameter also make the object of PlaceMark and Provide the object of place class and Add the Placemark object to MapView as an Annotation.

– (void)parserDidEndDocument:(NSXMLParser *)parser{
NSLog(@”Array = %@”,self.arrResult);

float latitude= [[[self.arrResult objectAtIndex:0] valueForKey:@”lat”] floatValue];
float longitude=[[[self.arrResult objectAtIndex:0] valueForKey:@”lng”] floatValue];

Place* home = [[Place alloc] init];
home.name = [[self.arrResult objectAtIndex:0] valueForKey:@”formatted_address”];
home.latitude = latitude;
home.longitude = longitude;

PlaceMark *from = [[PlaceMark alloc] initWithPlace:home];
[self.mView addAnnotation:from];
[self centerMap];
}

Step 8:For Annotation here you have to Integrate MKMapView’s Annotation Delegate methods as shown.

#pragma mark – MapView Annotation

– (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
// if it’s the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;

// try to dequeue an existing pin view first
static NSString* AnnotationIdentifier = @”AnnotationIdentifier”;
MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
pinView.animatesDrop=YES;
pinView.canShowCallout=YES;
pinView.pinColor=MKPinAnnotationColorPurple;
return pinView;
}

You can download the sample code From Here.

 

 

 

Advertisements

How to add custom fonts to an iPhone app?


Hello Friends,

Once again coming with simple but important things.How we customize the fonts.

This is only available for SDK 4.0 and above.

1.Add your custom font files into your project using XCode as resources.

2.Add a key to your info.plist file called “Fonts provided by application” ( Used to be called UIAppFonts).

3.It’s an array key.

4.For each font you have, enter the full name of your font file (including the extension).

5.Save info.plist.

6.Now in your application you can simply call [UIFont fontWithName:@”CustomFontName” size:12] to get the custom font to use with your UILabels and UITextView.

7.“CustomFontName” is not the font’s file name. It is the font name registered in the operating system. For example, if you try to use “Bauhaus Medium BT.ttf”, the “CustomFontName” should be “Bauhaus Md BT”, no extension “.ttf” is needed. You need to install the font in your system to find out what name it is. Some fonts have 2 names, you may need FontForge to find out and try which one works.

8.So far I found out that both ttf and otf format work out of the box. I haven’t tested other font formats yet.

How to Launching Other Apps within an iPhone Application?


Here I am going to explain you few key feature using NSURL and UIApplication.

Examples of some of the key applications that you can launch via URL are:

Launch Google Maps


Launch Apple Mail


Dial a Phone Number


Launch the SMS Application


Launch the Browser


Launch the AppStore

Launching the Browser from within an iPhone application

 

 

Launch Google Maps

The URL string for launching Google Maps with a particular keyword follows this structure:
http://maps.google.com/maps?q=${QUERY_STRING}
The only trick to this is to ensure that the value for the ${QUERY_STRING} is properly URL encoded. Here is a quick example of how you would launch Google Maps for a specific address:
// Create your query …
NSString* searchQuery = @”1 Infinite Loop, Cupertino, CA 95014″;

// Be careful to always URL encode things like spaces and other symbols that aren’t URL friendly

searchQuery =  [addressText stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

// Now create the URL string …

NSString* urlString = [NSString stringWithFormat:@”http://maps.google.com/maps?q=%@&#8221;, searchQuery];

// An the final magic … openURL!
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlText]];

Launch Apple Mail
Also very useful, is the ability to enable a user to quickly send an email by launching the email client in compose mode and the address already filled out. The format of this URI should be familiar to anyone that has done any work with HTML and looks like this:

mailto://${EMAIL_ADDRESS}

For example, here we are opening the email application and filling the “to:” address with info@iosdevelopertips.com :
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@”mailto://info@iosdevelopertips.com”]];

Dial a Phone Number (iPhone Only)


You can use openURL: to dial a phone number. One advantage this has over other URLs that launch applications, is that the dialer will return control back to the application when the user hits the “End Call” button.
Anyone familiar with J2ME or WML will find this URL scheme familiar:

tel://${PHONE_NUMBER}

Here is an example of how we would dial the number (900) 867-9999:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@”tel://9008679999″]];
NOTE When providing an international number you will need to include the country code.

Launch the SMS Application

Also not supported by the iPod Touch, is the ability to quickly setup the SMS client so that your users can quickly send a text message. It is also possible to provide the body of the text message.
The format looks like this:

sms:${PHONENUMBER_OR_SHORTCODE}

NOTE: Unlike other URLs, an SMS url doesn’t use the “//” syntax. If you add these it will assume it is part of the phone number which is not.

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@”sms:55555″]];

NOTE: According to the official SMS specification, you should be able to send a body as well as the phone number by including “?body=” parameter on the end of the URL … unfortunately Apple doesn’t seem to support this standard.

Launching the AppStore

Finally, it is worth noting that you can launch the AppStore and have the “buy” page of a specific application appear. To do this, there is no special URL scheme. All you need to do is open up iTunes to the application you want to launch; right-click on the application icon at the top left of the page; and select Copy iTunes Store URL .
The URL will look something like this:

http://itunes.apple.com/in/app/angry-birds-space-hd-free/id526337775?mt=8

Launching the AppStore URL is exactly the same as you would launch the browser. Using the link above, here is an example of how we would launch the AppStore:

NSURL *appStoreUrl = [NSURL URLWithString:@”http://itunes.apple.com/in/app/angry-birds-space-hd-free/id526337775?mt=8″%5D;
%5B%5BUIApplication sharedApplication] openURL:appStoreUrl];

 

Launching the Browser from within an iPhone application

It is sometimes nice to be able to launch a browser from within your applications. Though not as elegant as the use of a UIWebView, it is much easier.
NOTE Because it is possible for an application to bind itself to a URL (like Google Maps), this technique can also be used to launch other applications on the device.
Here is a simple example of how to open safari with a specific URL:

NSURL *url = [NSURL URLWithString:@”https://iosrider.wordpress.com”%5D;
[[UIApplication sharedApplication] openURL:url];

How to use Socialize in your iPhone/iPad native application?


Hi,

I have integrate Socialize in one of my sample code and believe me it’s amazing.it’s far better than any other sharing media.just visit this web site initially.http://www.getsocialize.com/.

It includes Email,Facebook and Twitter.I have Integrated Email and Twitter and working on Facebook as well.I am going to Explain you how to integrate it in your application.

Step 1: Click Here

Step 2: Choose 1 st option  Register and get your API keys.Once you have your API Key’s with you then follow step 3.

Step 3: When you click on DownLoad SDK for iOS you will get Framework for Integration.

Step 4: Add Socialize framework to your Application with Copy option selected as shown in the image.

step 5:Add Required Framework as shown below.

CoreLocation.framework,MapKit.framework,MessageUI.framework,QuartzCore.framework,CoreGraphics.framework

step 6: Set other Linker Flag as shown below.

step 7: Import Header and Set up your Socialize Keys like this.

//import the socialize header
#import <Socialize/Socialize.h>

#pragma mark
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
    // set the socialize api key and secret, register your app here: http://www.getsocialize.com/apps/
    [Socialize storeConsumerKey:@"SOCIALIZE_CONSUMER_KEY"];
    [Socialize storeConsumerSecret:@"SOCIALIZE_CONSUMER_SECRET"];

    //your application specific code

    return YES;
}

Step 8: Include Socialize in your App!

// Header file

// Store the action bar in a property on your view controller

#import <Socialize/Socialize.h>

@interface CreateActionBarViewController : UIViewController
@property (nonatomic, retain) SocializeActionBar *actionBar;
@end
// Implementation file

// Instantiate the action bar in your view controller

- (void)viewDidLoad
{
    [super viewDidLoad];

    if (self.actionBar == nil) {
        self.actionBar = [SocializeActionBar actionBarWithKey:@"http://www.example.com/object/1234" name:@"Something" presentModalInController:self];
        [self.view addSubview:self.actionBar.view];
    }
}

Now your App is ready to display Socialize bar.Here I am giving you the Sample code with Twitter integration and update it once it get completed with Facebook as well.

Custom Calender For iPad


Hi,

I have implemented Custom Calender Control for iPad which is bit simple to implement.

Step 1: Add the Listed File into your Project.(I have Provided  all Listed Files.)

1.CustomCalendar.h

2.CustomCalendar.m

3.CustomCalendar.xib

4.TdCalendarView.h

4.TdCalendarView.m

Step 2: Now your 70% Task is completed.You need to Integrate the Delegate Methods only.

#pragma mark – CalendarViewDelegate methods
-(void)monthChanged:(CFGregorianDate)currentMonth viewLeftTop:(CGPoint)viewLeftTop height:(float)height{

}
-(void)selectDateChanged:(CFGregorianDate)selectDate{
}

-(void)beforeMonthChange:(TdCalendarView *)calendarView willto:(CFGregorianDate)currentMonth{

}

For More info Please check this images.

Here i am attaching the sample code for the same.

Draw Route Between two location


Hi All,

Here I am going to explain you how to draw route using two latitude and Longitude.Here you have to consider if any Sea or River comes between 2 location then route drawing is not possible.

Step 1:Please check the following image for Framework required and predefined classes

if you want you will get all the files with sample code at the end of the post.

Step 2: Import Required files in your ViewController and Provide the 2 different Location’s Latitude and Longitude.Please follow this 2 images accordingly.

OutPut

You can Grab this code from Here:  

iPhone/iPad – Adding overlay


This blog is about adding custom overlay to a map. Overlays like polygon and circle can be added to the map. For instance you want to highlight or outline an area of a state or states in a country. In my application i have outlined all the states in US.

MKMapKit provides MKPolygon class and add overlay to achieve this. This can be done with easy four steps
1. Initialize map
2. Get coordinates
3. Create Polygon and add to map.
4. Implement delegate
1. Initialize Map :
Initialize the map view and add it as subview.

MKMapView _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 28, 360, 250)];

MKCoordinateRegion region;

region.center.latitude = 42.5116;

region.center.longitude = -90.6290;

region.span.longitudeDelta = 26.0;

region.span.latitudeDelta = 26.0;

_mapView.showsUserLocation = NO;

[_mapView setScrollEnabled:YES];

[_mapView setRegion:region];

[_mapView setDelegate:self];

[self.view addSubview:_mapView];

2. Get Coordinates
Here in this example, i have outlined all the US states. So to draw a polygon we need coordinates of all the state. Coordinates can be saved in local file or local database. This is the link to get coordinates of all US state
3. CreatePolygon:
Below is the code to add polygon

NSMutableArray* points; (contains coordinates of particular state)

CLLocationCoordinate2D *coords =

malloc(sizeof(CLLocationCoordinate2D) * [points count]);

 

for(int idx = 0; idx < [points count]; idx++) {

CLLocation* location = [points objectAtIndex:idx];

coords[idx] = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);

}

polygon = [MKPolygon polygonWithCoordinates:coords count:[points count]];

free(coords);

[_mapView addOverlay:polygon];

 

3. Implement Delegate

 

 

– (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id )overlay

{

MKPolygonView *polygonView = [[[MKPolygonView alloc] initWithPolygon:overlay] autorelease];

polygonView.lineWidth = 0.5;

polygonView.strokeColor = [UIColor whitecolor];

polygonView.fillColor = [[UIColor colorWithRed:0.9176 green:0.9098 blue:0.8117 alpha:1.0] colorWithAlphaComponent:0.5];;

return polygonView;

}

 

zooming also taken care by this implementation. We dont need to do extra coding to handle zoom.

How to Move Image using Touch Function in iPhone?


This is the very simple application. In this application we will see how to image move using touch. So let see how it will work.

Step 1 : Open the Xcode, Create a new project using View Base application. Give the application “Touch_Image”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: We need add also two resource in the project.

Step 4: In the Touch_ImageViewController.h file, make the following changes.

#import <UIKit/UIKit.h> 

@interface Touch_ImageViewController : UIViewController {
UIImageView *image;
}
@property (nonatomic,retain) IBOutlet UIImageView *image;
@end

Step 5: Double click the Touch_ImageViewController.xib file and open it to the interface builder. First select the view and bring up Attribute Inspector and change the background color. Drag the label from the library and place it to the view window. Select the label and bring up Attributes Inspector and the text to “Touch Anywhere” . Now drag the ImageView from the library and place it to the view window. Select the Image View from the view and bring up Attribute Inspector and select the litchi-big.png image. Connect File’s Owner icon to the image view and select image. Now save the .xib file, save it and go back to the Xcode.

Step 6: Open the Touch_ImageViewController.m file and make the following changes:

#import “Touch_ImageViewController.h” 

@implementation Touch_ImageViewController

@synthesize image;

– (void)dealloc
{
[super dealloc];
}

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:touch.view];
image.center = touchLocation;
}

– (void)didReceiveMemoryWarning
{

[super didReceiveMemoryWarning];

}

#pragma mark – View lifecycle

– (void)viewDidUnload
{
[super viewDidUnload];
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

 

Step 7: Now compile and run the application on the Simulator.

How to take screenshots within your Application.


iPhone / iPod touch allows you to make screenshots (saves the contents as an image) by pressing both home and power button, although many users don’t know this functionality. If you go to your camera roll or sync photos with your computer, every screenshot you make is an image 320 x 480 px.

Today I will show you how to make a screenshot of arbitrary size using Quartz. What does arbitrary size mean? Well you can not only save the smaller part of your screen, but, if you for example have bigger view than 320×480 px you can save it all, not only the visible part.

Before you start, you have to add the QuartzCore framework to the project.

#import <QuartzCore/QuartzCore.h>

You can add this line in either header (.h) or implementation file (.m).

Now it’s time to add the method which will make a screenshot and explain how it works:

-(void)saveToCameraRoll {
	UIGraphicsBeginImageContext(self.view.bounds.size);
	[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
	UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	UIImageWriteToSavedPhotosAlbum(viewImage, self, nil, nil); 

	/* 
	flashView.alpha = 1;
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.5];
	flashView.alpha = 0;
	[UIView commitAnimations];
	UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil message:@"Photo saved to your camera roll" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	[alert release];
	*/
}

I’ve implemented the saveToCameraRoll method were first five lines do everything you need. It’s quite difficult to discuss it, as long as I never mentioned about Quartz drawingcontextslayers… But, first line creates the context of our view (UIViewController’s self.view) size. Using that context’sframe (it’s not frame properly speaking) it contents is rendered (2nd line) and saved to anviewImage. 4th line is closing the context as we do not need it anymore, and the 5th line putsviewImage to the Camera Roll.

How about the part in the comment ( /* and */ )? Well it’s my idea how to copy the animation iPhone uses while making the screenshot using home and power buttons. I created the flashView – simple white view of the same size of my self.view most time 100% transparent. When the userdecides to create a screenshot using a button I provided in the application, flashView become visible and during half a second it’s transparent again. And the alert to inform what has just happen.

Please remember that above method saves the whole self.view and all it’s subviews. So whatever is a subview of self.view will be saved as well. You can change the alpha property of anything you don’t want to save and reveal what’s behind it, and after screenshot was made bring alpha to normal. While making a screenshot as long as it will be one procedure – one task user won’t see any changes in interface. Example:

-(void)saveToCameraRoll {	topView.alpha = 0;

	UIGraphicsBeginImageContext(self.view.bounds.size);
	[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
	UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	UIImageWriteToSavedPhotosAlbum(viewImage, self, nil, nil); 
	topView.alpha = 1;

}

As always (don’t thank me) I provided an sample project. It alows you to make screenshot of whole iPhone screen (320 x 480 px), only central part (320 x 240 px) and again the whole iPhone screen without button on the bottom.

 

Thanks goes to http://chris-software.com/

You can get the source code from here

 

How to change iPhone/iPad Navigation Bar Title text color and other Property?


Hi,

In iPhone/iPad several times we need to develop some custom controls or we need to change existing attribute.same way here i am going to explain how to change UINavigationbar’s title property like  font,color,size etc.

You need to use a UILabel as the titleView of the navigationItem.

The label should:

  • Have a clear background color (label.backgroundColor = [UIColor clearColor]).
  • Use bold 20pt system font (label.font = [UIFont boldSystemFontOfSize: 20.0f]).
  • Have a shadow of black with 50% alpha (label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]).
  • You’ll want to set the text alignment to centered as well (label.textAlignment = UITextAlignmentCenter).

Set the label text color to be whatever custom color you’d like. You do want a color that doesn’t cause the text to blend into shadow, which would be difficult to read.

I worked this out through trial and error, but the values I came up with are ultimately too simple for them not to be what Apple picked. 🙂

If you want to verify this, drop this code into initWithNibName:bundle: inPageThreeViewController.m of Apple’s NavBar sample. This will replace the text with a yellow label. This should be indistinguishable from the original produced by Apple’s code, except for the color.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {   
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    
 if (self)     {         // this will appear as the title in the navigation bar    
     UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];      
   label.backgroundColor = [UIColor clearColor];         
 label.font = [UIFont boldSystemFontOfSize:20.0];       
   label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];       
   label.textAlignment = UITextAlignmentCenter;      
   label.textColor = [UIColor yellowColor]; // change this color      
   self.navigationItem.titleView = label;          
 label.text = NSLocalizedString(@"PageThreeTitle", @"");       
   [label sizeToFit];    
 }    
 return self;
 }