How to add UINavigationController to UITabbarController Programatically?


Hi,

Today I am going to Explain you How to Add UINavigation Controller to UITabbarController.

  • When you add UIViewController to UIWindow Your Application become ViewControllerBase(SingleView) Application.
  • When you add UIViewController to UINavigationController your application become NavigationBased(Master-Detail) Application.
  • When you add UIViewController/UINavigationController to your UITabbarController Your application become Tabbased Application.

so here we are using the same concept that add your Navigation Controller to UITabbarController so you will get Push/Pop effect in UITabbar Controller.

//Initialize tabbar Controller and All Navigation Controllers are added into Tabbar Controller
self.tabbar = [[UITabBarController alloc] init];
NSArray *arrNVControllers = [NSArray arrayWithObjects:nav1,nav2,nav3,nav4, nil];

self.tabbar.viewControllers = arrNVControllers;

Download the sample code from Here

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.

 

 

 

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];

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 work with Core Motion Gyroscope?


It’s a simple app that utilizes Core Motion to roll an object on screen in the direction that the user is rolling the device. Hold the device upright (in portrait mode) and rotate clockwise/counter-clockwise.

You can grab the source code directly below:

Gyroscope.zip

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.