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 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.

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 Generate QR Code using Google Api for iPhone/iPad?


Hi,

I have found one very simple way how to generate QR Code using Google Api.Just take 1 UIWebView in my code I have taken IBOutlet UIWebView *webView; and I want add this Much of Information in My QR Code.

1.Business Name

2.First Name and  Last Name

3.Physical Address and phone

4.Website

I have also taken 1 Button Event named here is QRcodeTapped.I am receiving all the Value from NSDictionary.Please check the bellowed methods.

– (IBAction)QRcodeTapped:(id)sender {

NSLog(@”d==%@”,[d valueForKey:@”QR Business Name”]);

NSLog(@”d==%@”,[d valueForKey:@”QR First Name”]);

NSLog(@”d==%@”,[d valueForKey:@”QR Last Name”]);

NSLog(@”d==%@”,[d valueForKey:@”QR  Last Name”]);

NSLog(@”d==%@”,[d valueForKey:@”QR Physical Address”]);

NSLog(@”d==%@”,[d valueForKey:@”QR Physical City”]);

NSLog(@”d==%@”,[d valueForKey:@”QR Physical State”]);

NSLog(@”d==%@”,[d valueForKey:@”QR Physical Zip”]);

NSLog(@”d==%@”,[d valueForKey:@”QR Physical Zip Plus 4″]);

NSLog(@”d==%@”,[d valueForKey:@”QR Website”]);

//this url has several parameters which is passed here. After that don’t Forget NSUTF8StringEncoding.

NSString *url=[NSString stringWithFormat:@”http://chart.apis.google.com/chart?cht=qr&chs=200×200&chl=MECARD:ORG%@CN%@%@CTEL%@CADR%@%@%@%@%@CEMAIL%@&#8221;,[d valueForKey:@”QR Business Name”],[d valueForKey:@”QR First Name”],[d valueForKey:@”QR Last Name”],[d valueForKey:@”QR Phone”],[d valueForKey:@”QR Physical Address”],[d valueForKey:@”QR Physical City”],[d valueForKey:@”QR Physical State”],[d valueForKey:@”QR Physical Zip”],[d valueForKey:@”QR Physical Zip Plus 4″],[d valueForKey:@”QR Website”]];

url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

//Create a URL object.

NSURL *Curl=[NSURL URLWithString:url];

//URL Requst Object

NSURLRequest *request = [NSURLRequest requestWithURL:Curl];

//Load the request in the UIWebView.

[webView loadRequest:request];

}

Grab the Sample Code from Here

How to add Email and Message in your native application?


Hi,

See new sample code “MessageComposer” which includes both Mail and Messages features.

This application shows how to target older OS versions while building with newly released APIs. It also illustrates how to use the MessageUI framework to edit and send email messages from within your application.

Tap the “Compose Mail” button to display an email composition interface if your device is running iPhone OS 3.0 or launch the Mail application, otherwise.

Step 1:

Add MessageUI.framework to your Application.Add this Header file to the .h file and Provide delegate of it as shown below.

#import <MessageUI/MessageUI.h>

#import <MessageUI/MFMailComposeViewController.h>

@interface MailComposerViewController : UIViewController <MFMailComposeViewControllerDelegate>

{

IBOutlet UILabel *message;

}

@property (nonatomic, retain) IBOutlet UILabel *message;

-(IBAction)showPicker:(id)sender;

-(void)displayComposerSheet;

-(void)launchMailAppOnDevice;

 

Step 2:Now write the code for mail.

-(IBAction)showPicker:(id)sender

{

// This sample can run on devices running iPhone OS 2.0 or later

// The MFMailComposeViewController class is only available in iPhone OS 3.0 or later.

// So, we must verify the existence of the above class and provide a workaround for devices running

// earlier versions of the iPhone OS.

// We display an email composition interface if MFMailComposeViewController exists and the device can send emails.

// We launch the Mail application on the device, otherwise.

 

Class mailClass = (NSClassFromString(@”MFMailComposeViewController”));

if (mailClass != nil)

{

// We must always check whether the current device is configured for sending emails

if ([mailClass canSendMail])

{

[self displayComposerSheet];

}

else

{

[self launchMailAppOnDevice];

}

}

else

{

[self launchMailAppOnDevice];

}

}

 

 

#pragma mark –

#pragma mark Compose Mail

 

// Displays an email composition interface inside the application. Populates all the Mail fields.

-(void)displayComposerSheet

{

MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];

picker.mailComposeDelegate = self;

 

[picker setSubject:@”Hello from Ankit Vyas!”];

// Set up recipients

NSArray *toRecipients = [NSArray arrayWithObject:@”first@example.com”];

NSArray *ccRecipients = [NSArray arrayWithObjects:@”second@example.com”, @”third@example.com”, nil];

NSArray *bccRecipients = [NSArray arrayWithObject:@”fourth@example.com”];

 

[picker setToRecipients:toRecipients];

[picker setCcRecipients:ccRecipients];

[picker setBccRecipients:bccRecipients];

 

// Attach an image to the email

NSString *path = [[NSBundle mainBundle] pathForResource:@”rainy” ofType:@”png”];

NSData *myData = [NSData dataWithContentsOfFile:path];

[picker addAttachmentData:myData mimeType:@”image/png” fileName:@”rainy”];

 

// Fill out the email body text

NSString *emailBody = @”It is raining in sunny California!”;

[picker setMessageBody:emailBody isHTML:NO];

 

[self presentModalViewController:picker animated:YES];

[picker release];

}

// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.

– (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error

{

message.hidden = NO;

// Notifies users about errors associated with the interface

switch (result)

{

case MFMailComposeResultCancelled:

message.text = @”Result: canceled”;

break;

case MFMailComposeResultSaved:

message.text = @”Result: saved”;

break;

case MFMailComposeResultSent:

message.text = @”Result: sent”;

break;

case MFMailComposeResultFailed:

message.text = @”Result: failed”;

break;

default:

message.text = @”Result: not sent”;

break;

}

[self dismissModalViewControllerAnimated:YES];

}

#pragma mark –

#pragma mark Workaround

// Launches the Mail application on the device.

-(void)launchMailAppOnDevice

{

NSString *recipients = @”mailto:first@example.com?cc=second@example.com,third@example.com&subject=Hello from California!”;

NSString *body = @”&body=It is raining in sunny California!”;

 

NSString *email = [NSString stringWithFormat:@”%@%@”, recipients, body];

email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

 

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];

}

#pragma mark –

#pragma mark Unload views

 

– (void)viewDidUnload

{

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

self.message = nil;

}

#pragma mark –

#pragma mark Memory management

– (void)dealloc

{

[message release];

[super dealloc];

}

for more detail Grab the Code From Here

How to Integrate iAd in your Application?


Hi,

Today I am going to discuss how apple iAd is integrated in our iPhone/iPad Native Application.It’s really a very simple task.I am dividing this task in 3 simple steps.

Step 1:

1.import iAd Framework to the Application.

2.Provide #import <iAd/iAd.h> in the particular controller where you want to show your Add.

3.Provide it’s delegate UIViewController <ADBannerViewDelegate>

4.Provide one  view to that particular ViewController.Assume I have taken

@property (weak, nonatomic) IBOutlet UIView *contentView;

Step 2:

Allocate it in ViewDidLoad method

– (void)viewDidLoad
{
_bannerView = [[ADBannerView alloc] init];
_bannerView.delegate = self;

[super viewDidLoad];
[self.view addSubview:_bannerView];
}

step 3:

Provides it’s delegate methods which i have mention bellowed.

– (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
_bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
} else {
_bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierLandscape;
}
[self layoutAnimated:duration > 0.0];
}

– (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
[self layoutAnimated:YES];
}

– (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
[self layoutAnimated:YES];
}

– (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
{

return YES;
}

– (void)bannerViewActionDidFinish:(ADBannerView *)banner
{

}
– (void)layoutAnimated:(BOOL)animated
{
if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
_bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
} else {
_bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierLandscape;
}

CGRect contentFrame = self.view.bounds;
CGRect bannerFrame = _bannerView.frame;
if (_bannerView.bannerLoaded) {
contentFrame.size.height -= _bannerView.frame.size.height;
bannerFrame.origin.y = contentFrame.size.height;
} else {
bannerFrame.origin.y = contentFrame.size.height;
}

[UIView animateWithDuration:animated ? 0.25 : 0.0 animations:^{
self.contentView.frame = contentFrame;
[self.contentView layoutIfNeeded];
_bannerView.frame = bannerFrame;
}];
}

and your Advertisement is ready.

You can take the source code from Here.

(In File Option click on Download Original)

Day-14 for iOS development


Click here for Lecture 14 which includes

1.UIImagePickerController( Getting still photos or video from the user either from camera or photo library)

2. MPMovie[View]PlayerController   ( How to play videos )

3. ALAssetsLibrary   (How to store images or videos in the user’s photo album)

4. Sounds  ( How to play simple sounds and record simple audio snippets)