Tuesday, 7 July 2015

Date Picker for IOS

View Controller.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property(nonatomic, strong) IBOutlet UITextField *text2;

@property(nonatomic,strong)IBOutlet UIToolbar *toolbar;

@end




View Controller.m

#import "ViewController.h"

@interface ViewController ()
{
    UIDatePicker *datepicker;
}
@end

@implementation ViewController
@synthesize toolbar;
@synthesize text2;

- (void)viewDidLoad
{
    [super viewDidLoad];

    datepicker = [[UIDatePicker alloc]init];
    datepicker.datePickerMode = UIDatePickerModeDate;
    toolbar = [[UIToolbar alloc] init];
    toolbar.barStyle = UIBarStyleBlackTranslucent;
    [toolbar sizeToFit];
   
   
    UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneClicked:)];
    [toolbar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft, doneButton, nil]];
    text2.inputAccessoryView = toolbar;
   
    text2.inputView = datepicker;
   
}

-(void)doneClicked:(id) sender
{
    NSDateFormatter *formater = [[NSDateFormatter alloc]init];
    [formater setDateFormat:@"dd/MM/yyyy"];
    self.text2.text= [NSString stringWithFormat:@"%@",[formater stringFromDate:datepicker.date]];
    [self.text2 resignFirstResponder];
}
 

Friday, 26 June 2015

MapView With MkAnnotation

ViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface ViewController : UIViewController<MKMapViewDelegate>
{
    IBOutlet MKMapView *mapview;
}
- (IBAction)userlocation:(id)sender;

//- (IBAction)backahmedabad:(id)sender;

@end


ViewController.m

#import "ViewController.h"
#import "MkAnnotation.h"

@interface ViewController ()
{
    NSArray *annotations;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
    mapview.delegate = self;
    mapview.showsUserLocation = YES;
    [self addAnnotations];
   
}

-(void) addAnnotations {
    MkAnnotation *annotation1 = [[MkAnnotation alloc]initWithTitle:@"Nehrunagar" subTitle:@"Ahmedabad" andCoordinates:CLLocationCoordinate2DMake(23.022479000000000000, 72.542987199999970000)];
    annotation1.tag = 1;
   
    MkAnnotation *annotation2 = [[MkAnnotation alloc]initWithTitle:@"Income Tax" subTitle:@"Ahmedabad" andCoordinates:CLLocationCoordinate2DMake(23.039567700000000000, 72.566004499999960000)];
    annotation2.tag = 2;
   
    annotations = @[annotation1,annotation2];
    [mapview addAnnotation:annotation1];
    [mapview showAnnotations:annotations animated:YES];
}

- (MKPinAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    if([annotation isKindOfClass:[MKUserLocation class]]){
        return nil;
    }
    static NSString *identifier = @"identifier";
    MKPinAnnotationView *pinAnnotation = (MKPinAnnotationView *)[mapview dequeueReusableAnnotationViewWithIdentifier:identifier ];
    MkAnnotation *ann = (MkAnnotation *)annotation;
    if(pinAnnotation == nil)
    {
        pinAnnotation = [[MKPinAnnotationView alloc]initWithAnnotation:ann reuseIdentifier:identifier];
    }
    else
        pinAnnotation.annotation = ann;
    if(ann.tag ==1)
    {
        pinAnnotation.pinColor = MKPinAnnotationColorGreen;
    }
    else if(ann.tag == 2){
        pinAnnotation.pinColor = MKPinAnnotationColorPurple;
    }
   
    pinAnnotation.canShowCallout =YES;
    pinAnnotation.draggable = YES;
    return pinAnnotation;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)userlocation:(id)sender
{
    [mapview setCenterCoordinate:mapview.userLocation.coordinate animated:YES];
}

- (IBAction)backahmedabad:(id)sender {
    MkAnnotation *ann1 = (MkAnnotation *)[annotations firstObject];
    [mapview setCenterCoordinate:ann1.coordinate animated:YES ];
}
@end


MkAnnotation.h

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface MkAnnotation : NSObject<MKAnnotation>

@property(nonatomic,readwrite)NSInteger *tag;
@property(nonatomic,copy)NSString *title;
@property(nonatomic,copy)NSString *subtitle;
@property(nonatomic,readwrite)CLLocationCoordinate2D coordinate;

-(id)initWithTitle:(NSString *)title subTitle:(NSString *)subTitle andCoordinates:(CLLocationCoordinate2D)coordinate;
@end


MkAnnotation.m

#import "MkAnnotation.h"

@implementation MkAnnotation
@synthesize tag;
@synthesize title = _title;
@synthesize subtitle = _subtitle;
@synthesize coordinate = _coordinate;
-(id)initWithTitle:(NSString *)title subTitle:(NSString *)subTitle andCoordinates:(CLLocationCoordinate2D)coordinate;{

    self  = [super init];
    if(self){
        _title = title;
        _subtitle = subTitle;
        _coordinate = coordinate;
    }
    return self;
}
@end

Local Notification

 AppDelegate.m

#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    return YES;
}
                           
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
   
   
    NSDate *alarmTime = [[NSDate date]dateByAddingTimeInterval:5.0];
    UIApplication *app = [UIApplication sharedApplication];
    UILocalNotification *notifyAlarm = [[UILocalNotification alloc]init];
    if(notifyAlarm){
        notifyAlarm.fireDate = alarmTime;
        notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
        notifyAlarm.repeatInterval = 0;
        notifyAlarm.soundName = @"";
        notifyAlarm.alertBody = @"Hello Notification";
        [app scheduleLocalNotification:notifyAlarm];
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *oldnotification = [app scheduledLocalNotifications];
    if([oldnotification count]>0)
    {
        [app cancelAllLocalNotifications];
    }
   
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

Thursday, 25 June 2015

Sqlite DataBase(Save And Find)

ViewController.h

#import <UIKit/UIKit.h>
#import <sqlite3.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UITextField *name;
@property (strong, nonatomic) IBOutlet UITextField *address;
@property (strong, nonatomic) IBOutlet UITextField *phone;
@property (strong, nonatomic) IBOutlet UILabel *status;

- (IBAction)SaveData:(id)sender;
- (IBAction)FindData:(id)sender;



@property (strong, nonatomic) NSString *databasePath;
@property (nonatomic) sqlite3 *contactDB;

@end


ViewController.m

 #import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
    NSString *docsDir;
    NSArray *dirPaths;
   
    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(
                                                   NSDocumentDirectory, NSUserDomainMask, YES);
   
    docsDir = dirPaths[0];
   
    // Build the path to the database file
    _databasePath = [[NSString alloc]
                     initWithString: [docsDir stringByAppendingPathComponent:
                                      @"user.sqlite"]];
   
    NSFileManager *filemgr = [NSFileManager defaultManager];
   
    if ([filemgr fileExistsAtPath: _databasePath ] == NO)
    {
        const char *dbpath = [_databasePath UTF8String];
       
        if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt =
            "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER , NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
           
            if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                _status.text = @"Failed to create table";
            }
            sqlite3_close(_contactDB);
        } else {
            _status.text = @"Failed to open/create database";
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)SaveData:(id)sender {
    sqlite3_stmt    *statement;
    const char *dbpath = [_databasePath UTF8String];
   
    if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
    {
       
        NSString *insertSQL = [NSString stringWithFormat:
                               @"INSERT INTO CONTACTS (name, address, phone) VALUES (\"%@\", \"%@\", \"%@\")",
                               _name.text, _address.text, _phone.text];
       
        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(_contactDB, insert_stmt,
                           -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            _status.text = @"Contact added";
            _name.text = @"";
            _address.text = @"";
            _phone.text = @"";
        } else {
            _status.text = @"Failed to add contact";
        }
        sqlite3_finalize(statement);
        sqlite3_close(_contactDB);
    }
}

- (IBAction)FindData:(id)sender {
    const char *dbpath = [_databasePath UTF8String];
    sqlite3_stmt    *statement;
   
    if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
    {
        NSString *querySQL = [NSString stringWithFormat:
                              @"SELECT address, phone FROM contacts WHERE name=\"%@\"",
                              _name.text];
       
        const char *query_stmt = [querySQL UTF8String];
       
        if (sqlite3_prepare_v2(_contactDB,
                               query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            if (sqlite3_step(statement) == SQLITE_ROW)
            {
                NSString *addressField = [[NSString alloc]
                                          initWithUTF8String:
                                          (const char *) sqlite3_column_text(
                                                                             statement, 0)];
                _address.text = addressField;
                NSString *phoneField = [[NSString alloc]
                                        initWithUTF8String:(const char *)
                                        sqlite3_column_text(statement, 1)];
                _phone.text = phoneField;
                _status.text = @"Match found";
            } else {
                _status.text = @"Match not found";
                _address.text = @"";
                _phone.text = @"";
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(_contactDB);
    }
}
@end

Map View

ViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface MapViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate,MKAnnotation>
{
    IBOutlet MKMapView *MpData;
    CLLocationManager *locationManager;
}
@end


ViewController.m

#import "MapViewController.h"

@interface MapViewController ()
{
    MKPinAnnotationView *pinView;
    CLLocation *currentLocation ;
    MKPointAnnotation *myAnnotation;
    UISegmentedControl *segmentedControl;
}
@end

@implementation MapViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    NSArray *itemArray = [NSArray arrayWithObjects: @"Red", @"Green", @"Purple", nil];
    segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
    segmentedControl.frame = CGRectMake(35, 70, 250, 35);
    segmentedControl.segmentedControlStyle =UISegmentedControlStylePlain;
    [segmentedControl addTarget:self action:@selector(MySegmentControlAction:) forControlEvents: UIControlEventValueChanged];
    segmentedControl.selectedSegmentIndex = 0;
    [self.view addSubview:segmentedControl];
  
   // [self.view addSubview:scroll];
     locationManager = [[CLLocationManager alloc] init];
    [self CurrentLocation];
  
    myAnnotation = [[MKPointAnnotation alloc] init];
    myAnnotation.coordinate = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
   
    myAnnotation.title = @"Hi.Pin Demo";
    myAnnotation.subtitle = @"Change Pin Color ";
    myAnnotation.coordinate=MpData.centerCoordinate;
    [MpData addAnnotation:myAnnotation];
   
   
    // Do any additional setup after loading the view.
}
- (void)MySegmentControlAction:(UISegmentedControl *)segment
{
    //MKPinAnnotationView *result = [[MKPinAnnotationView alloc] initWithAnnotation:myAnnotation reuseIdentifier:Nil];
    //[myAnnotation setCoordinate:currentLocation.coordinate];
    if(segment.selectedSegmentIndex == 0)
    {
        //result.backgroundColor=[UIColor redColor];
        pinView.pinColor=MKPinAnnotationColorRed;

    }
    else if(segment.selectedSegmentIndex==1)
    {
        //result.backgroundColor=[UIColor greenColor];
        pinView.pinColor=MKPinAnnotationColorGreen;
    }
    else if (segment.selectedSegmentIndex==2)
    {
       // result.backgroundColor=[UIColor blueColor];
         pinView.pinColor=MKPinAnnotationColorPurple;
    }
}

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotationPoint
{
    static NSString *annotationIdentifier = @"annotationIdentifier";
   
    pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotationPoint reuseIdentifier:annotationIdentifier];
    pinView.pinColor = MKPinAnnotationColorPurple;
    return pinView;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    currentLocation = newLocation;
   
   /* if (currentLocation != nil) {
        longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
        latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    }*/
   
}
- (void)CurrentLocation
{
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
   
    [locationManager startUpdatingLocation];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

XML Parser

ViewController.h

#import <UIKit/UIKit.h>
#define ITEM_NAME @"name"
#define FOOD @"food"
#define ITEM_PRICE @"price"
#define ITEM_DESCRIPTION @"description"
#define ITEM_CALORIES @"calories"

@interface ViewController : UIViewController<NSXMLParserDelegate,UITableViewDataSource,UITableViewDelegate>
{
    IBOutlet UITableView *tblxml;
    NSMutableArray *arraydata;
}
@end


ViewController.m

  #import "ViewController.h"

@interface ViewController ()
{
    NSXMLParser *parser;
   
    NSMutableDictionary *currentData;
    NSString *currentElement;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:@"food" ofType:@"xml"];
   
    parser = [[NSXMLParser alloc]initWithContentsOfURL:[NSURL fileURLWithPath:xmlFilePath]];
   
    [parser setDelegate:self];
    [parser parse];
   
    if (!arraydata)
    {
        arraydata = [[NSMutableArray alloc]init];
    }

}


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDic
{
    NSLog(@"Did start element");
   
    currentElement = elementName;
   
    if ( [elementName isEqualToString:FOOD])
    {
        if (!currentData) {
            currentData = [[NSMutableDictionary alloc]init];
        }
       
        NSLog(@"found rootElement");
        return;
    }
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"Did end element");
   
    if ([elementName isEqualToString:ITEM_PRICE]) {
        currentElement = elementName;
    }else if ([elementName isEqualToString:ITEM_NAME]){
        currentElement = elementName;    }
    else if ([elementName isEqualToString:ITEM_DESCRIPTION]){
        currentElement = elementName;
    }else if ([elementName isEqualToString:ITEM_CALORIES]){
        currentElement = elementName;
    }else{
        currentElement = @"";
    }
   
    if ([elementName isEqualToString:FOOD])
    {
        if (arraydata == nil) {
            arraydata= [[NSMutableArray alloc]init];
        }
       
        [arraydata addObject:[currentData copy]];
        [currentData removeAllObjects];
    }

}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if ([string rangeOfString:@"\n"].location == NSNotFound) {
        if ([currentElement isEqualToString:ITEM_PRICE]) {
            [currentData setObject:string forKey:ITEM_PRICE];
        }else if ([currentElement isEqualToString:ITEM_NAME]){
            [currentData setObject:string forKey:ITEM_NAME];
        }else if ([currentElement isEqualToString:ITEM_DESCRIPTION]){
            [currentData setObject:string forKey:ITEM_DESCRIPTION];
        }else if ([currentElement isEqualToString:ITEM_CALORIES]){
            [currentData setObject:string forKey:ITEM_CALORIES];
        }
    }
   
}

-(void)parserDidStartDocument:(NSXMLParser *)parser
{
    NSLog(@"StartDocument");
   
}

- (void)parserDidEndDocument:(NSXMLParser *)parser{
   
    NSLog(@"%@",arraydata);
   
    [tblxml reloadData];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return arraydata.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
   
    NSDictionary *currentItemDetails = [arraydata objectAtIndex:indexPath.row];
   
    cell.textLabel.text = [currentItemDetails objectForKey:ITEM_NAME];
    cell.textLabel.text = [currentItemDetails objectForKey:ITEM_PRICE];
    cell.textLabel.text = [currentItemDetails objectForKey:ITEM_DESCRIPTION];
    cell.textLabel.text = [NSString stringWithFormat:@"Calories :: %@",  [currentItemDetails objectForKey:ITEM_CALORIES]];
   
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 125;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


JSON Parser


#import "ViewController.h"

@interface ViewController ()
{
    NSMutableDictionary *arraykey;
    NSMutableArray *arraydata;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://www.json-generator.com/api/json/get/bUyjbCQmxu?indent=2"]];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
    {
        if (!connectionError) {
            arraykey = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            arraydata = [[NSMutableArray alloc]init];
            [arraydata addObjectsFromArray:[[[arraykey objectForKey:@"items"]objectAtIndex:0] allKeys]];
            NSLog(@"%@",arraydata);
            NSLog(@"%@",arraykey);
            [tbljson reloadData];
        } else {
            NSLog(@"error: %@",[connectionError localizedDescription]);
        }
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arraydata.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reusecell"];
   
    if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reusecell"];
    }
   
   cell .textLabel.text = [arraydata objectAtIndex:indexPath.row];
   
    return cell;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end