Monday, 6 January 2014

How to Get Data , insert data and Delete data in SQLite

-(void)GetDataFromDB{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"RideRecord.sqlite"];/// Table Name
    
    NSMutableArray *arrayTemp = [[NSMutableArray alloc]init];
    
    sqlite3 *database2;
    
    if (sqlite3_open([dbPath UTF8String], &database2) == SQLITE_OK) {
        
        const char *sqlStatement3 = "select * from NewRideTable";//Table Name
        
        sqlite3_stmt *compileStatement;
        
        if (sqlite3_prepare_v2(database2, sqlStatement3, -1, &compileStatement, NULL) == SQLITE_OK) {
            
            
            while (sqlite3_step(compileStatement) == SQLITE_ROW) {
                
                NSLog(@"one record");
                
                NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,0)] forKey:@"TimeStamp"];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,1)] forKey:@"Speed"];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,2)] forKey:@"Distance"];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,3)] forKey:@"LatitudeDegrees"];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,4)] forKey:@"LongitudeDegrees"];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,5)] forKey:@"Altitude"];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,6)] forKey:@"Temperature"];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,7)] forKey:@"HeartRate"];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,8)] forKey:@"Cadence"];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,9)] forKey:@"Powers"];
                [dict setObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compileStatement,10)] forKey:@"PointOrder"];

                [arrayTemp addObject:dict];
            }

            [dictRides setObject:arrayTemp forKey:@"Ridedata"];
            [dictRides retain];
            
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictRides
                                                               options:0
                                                                 error:nil];
            
            if (!jsonData) {
                NSLog(@"Error");
            } else {
                
                strRidesJson = [[NSString alloc] initWithBytes:[jsonData  bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
                [strRidesJson retain];
                NSLog(@"\n\n JSON String ==>> %@",strRidesJson);
                
            }
        }
    } else {

        NSLog(@"error in database");
    }
    sqlite3_close(database2);
}
-(void)InsertRideData{
    NSDate *date = [[NSDate alloc]init];
    strTimeStamp = [[NSString stringWithFormat:@"%@",date]retain];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"RideRecord.sqlite"];
    
    sqlite3 *database2;
    
    if (sqlite3_open([dbPath UTF8String], &database2) == SQLITE_OK) {
        static sqlite3_stmt *compiledStatement = nil;
//        NSString *insertSQL = @"INSERT INTO NewRideTable (TimeStamp,Speed,Distance,LatitudeDegrees,LongitudeDegrees,Altitude,Temperature,HeartRate,Cadence,Powers,PointOrder) VALUES ('2013-11-20 13:27:52 +0000', '5.169240','20','22.996843','72.498082','72.918686','8','67','20','200','72.498082','1')";
        NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO NewRideTable (TimeStamp,Speed,Distance,LatitudeDegrees,LongitudeDegrees,Altitude,Temperature,HeartRate,Cadence,Powers,PointOrder) VALUES ('%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%d')",strTimeStamp,strSpeed,strDistance,strLat,strLong,strAltitude,strTemperture,strHeartrateVal,lblCadenceVal.text,lblPowerVal.text,PointOrder];
        [insertSQL retain];
        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(database2,insert_stmt, -1, &compiledStatement, NULL);
//        if (sqlite3_prepare_v2(database2, insert_stmt, -1, &compiledStatement, NULL) == SQLITE_OK) {
        if(sqlite3_step(compiledStatement)==SQLITE_DONE)
        {
            NSLog(@"Working");
        }
        sqlite3_finalize(compiledStatement);
    }
    sqlite3_close(database2);
    PointOrder++;
}
-(void) DeleteNewRideRecords {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"RideRecord.sqlite"];
    
    sqlite3 *database2;
    
    if (sqlite3_open([dbPath UTF8String], &database2) == SQLITE_OK) {
        NSString *query = @"delete from NewRideTable";
        const char *sqlStatement = [query UTF8String];
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database2, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            // Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Read the data from the result row
                NSLog(@"result is here");
            }
            
            // Release the compiled statement from memory
            sqlite3_finalize(compiledStatement);
        }
    }
    PointOrder = 0;
    sqlite3_close(database2);

//    [self GetDataFromDB];

}

Wednesday, 4 December 2013

Display all Annotation pin on MapView

- (void)zoomToFitMapAnnotations:(MKMapView *)mapView {
    if ([mapView.annotations count] == 0) return;
    
    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;
    
    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;
    
    for(id<MKAnnotation> annotation in mapView.annotations) {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }
    
    MKCoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;
    
    // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;
    
    region = [mapView regionThatFits:region];
    [mapView setRegion:region animated:YES];
}



Thursday, 21 November 2013

See How to Find Latitude and Longitude from location name.


/// Required Framework
     1. CoreLocation and 2. MapKit.

Import this two file where you use bellow method

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

/// This bellow code work in < 5.0

  CLGeocoder* gc = [[CLGeocoder alloc] init];
    [gc geocodeAddressString:@"Set Your Location Name" completionHandler:^(NSArray *placemarks, NSError *error)
    {
        if ([placemarks count]>0)
        {
            // get the first one
            CLPlacemark* mark = (CLPlacemark*)[placemarks objectAtIndex:0];
            double lat = mark.location.coordinate.latitude;
            double lng = mark.location.coordinate.longitude;
            CLLocationCoordinate2D objCo;
            objCo.latitude = lat;
            objCo.longitude = lng;
            
            MKCoordinateRegion region;
            region.center = objCo;
            region.span.latitudeDelta = 0.03;
            region.span.longitudeDelta = 0.03;
            
            [objMapView setRegion:region animated:YES];// set region on your mapView
            MyAnnotation *ann = [[MyAnnotation alloc] init];// i just create this Annonation object for get and set location detail
            ann.title = strLocation;
            ann.subtitle = strDetailDesc;
            ann.anntag=11111;
            ann.coordinate = objCo;
            [objMapView addAnnotation:ann];
//            MKCoordinateRegion viewregion = MKCoordinateRegionMakeWithDistance(objCo, 0.03  , 0.03);
//            [self.objMapView setRegion:viewregion animated:YES];
        }

    }];


/// This is working in any ios

- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address{
    double latitude = 0, longitude = 0;
    NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    if (result) {
        NSScanner *scanner = [NSScanner scannerWithString:result];
        if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil]) {
            [scanner scanDouble:&latitude];
            if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil]) {
                [scanner scanDouble:&longitude];
            }
        }
    }
    CLLocationCoordinate2D center;
    center.latitude = latitude;
    center.longitude = longitude;
    return center;
}

=> In this above method if your location not found then you get lat-long 0.0000

you can use above method it like bellow...

CLLocationCoordinate2D objLocaton =[appDelegate geoCodeUsingAddress:@"ahmedabad"];

NSLog(@"Location:%f && %f",objLocaton.latitude, objLocaton.longitude);


How to convert NSMutableDictionary to JSONString...

NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
///Add records or any value and convert it like bellow...

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                               options:0
                                                                 error:nil];
            
if (!jsonData) {
      NSLog(@"Error");
} else {
                
      NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData  bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
      NSLog(@"\n\n JSON String ==>> %@",JSONString);
 }

Tuesday, 13 August 2013

Go to particular parent class from subclass

you can find that particular UIViewController from its navigationController's viewControllers array like bellow...

    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[YourViewController class]]) {
            //Do not forget to import that YourViewController.h
            
            [self.navigationController popToViewController:controller
                                                  animated:YES];
            break;
        }

    }

Wednesday, 29 May 2013

Watch or counter with NSTimer

take object of NSTimer and also int variable  in .h file like bellow..

    NSTimer *timer;
    int hours, minutes, seconds;
    int secondsLeft;

and just use it with bellow method

- (void)updateCounter:(NSTimer *)theTimer {
    secondsLeft++;
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    //lblTime.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    NSLog(@"\n%02d:%02d:%02d",hours,minutes,seconds);

}

-(void)countdownTimer{
    
    if([timer isValid])
    {
        [timer release];
    }
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
    [pool release];
}

See My Answer also converstion-of-seconds-in-minutes

Thursday, 18 April 2013

Convert some Special character to the Unicode/UTF 8 character and also Unicode to NSString....


    NSString *string = @"Hello & How % Are You?";
string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
string = [string stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];
    NSLog(@"\n\n ===>> Before ==>> %@",string);
    
    NSString *string2 = string;
string2 = [string2 stringByReplacingOccurrencesOfString:@"%20" withString:@" "];
string2 = [string2 stringByReplacingOccurrencesOfString:@"%26" withString:@"&"];
string2 = [string2 stringByReplacingOccurrencesOfString:@"%25" withString:@"%"];    
    NSLog(@"\n\n ===>> After ==>> %@",string2);

Here you get out put is:

===>> Before ==>> Hello%20%25%20How%20Are%20You?
====>> After ==>> Hello % How Are You?

See My answer from this link.. http://stackoverflow.com/questions/16081390/how-to-get-from-web-service-in-iphone/16081968#16081968

And also list of Unicode/UTF 8 Character Table.. http://www.utf8-chartable.de/