Tuesday, 4 March 2014

Set and get Date in NSString format or NSDate format with different date format with my bellow method

You can get date with string return type and also set date format in which you want to get date For Ex: dd-MMM-yyyy (i.e. 05-Mar-2014)

-(NSString *)changeDateFormat:(NSString*)stringDate dateFormat:(NSString*)dateFormat getwithFormat:(NSString *)getwithFormat{
    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    
    NSDate *date = [dateFormatter dateFromString:stringDate];
    [dateFormatter setDateFormat:getwithFormat];
    
    NSString *convertedString = [dateFormatter stringFromDate:date];
    NSLog(@"Converted String : %@",convertedString);
    return convertedString;
}

NSString  *stringVar  = [self changeDateFormat:yourDateString dateFormat:@"yyyy-MM-dd" getwithFormat:@"dd MMM yyyy"];// set your date string and its date format and after set your required new date format

You can get date with NSDate return type and also set date format in which you want to get date For Ex: dd-MMM-yyyy (i.e. 05-Mar-2014) same like above but here you get return date in NSDate.

-(NSDate *)convertStringToDate:(NSString *)date dateFormat:(NSString *)dateFormat getWithFormat:(NSString *)getWithFormat {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSDate *nowDate = [[NSDate alloc] init];
    [formatter setDateFormat:dateFormat];// set format here which format in string date
    date = [date stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
    nowDate = [formatter dateFromString:date];
    [formatter setDateFormat:getWithFormat];
    
    NSString *convertedString = [formatter stringFromDate:nowDate];
    nowDate = [formatter dateFromString:convertedString];
    // NSLog(@"date============================>>>>>>>>>>>>>>> : %@", nowDate);
    return nowDate;

}

set size of UILable with its content text

With my bellow method you can set UILable size with its content text.

-(CGRect)setDynamicHeight:(UILabel *)lbl{
    CGRect myLabelFrame = [lbl frame];
  
    NSString *text = lbl.text;
    CGFloat width = lbl.frame.size.width;
    UIFont *font = lbl.font;
    NSAttributedString *attributedText =
    [[NSAttributedString alloc]
     initWithString:text
     attributes:@
     {
     NSFontAttributeName: font
     }];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize size = rect.size;
    
    myLabelFrame.size.height = size.height;
    
    return myLabelFrame;

}

and use this method with my bellow code

    [yourLable setFrame:[self setDynamicHeight:yourLable]];

Monday, 3 March 2014

How to add animation in View for any view or any Control.



With bellow code you can set animation for any control or any view...

        CATransition *animation = [CATransition animation];
        [animation setDuration:1.0];// Set Duration
        [animation setType:kCATransitionPush];
        [animation setSubtype:kCATransitionFromTop];// set different type of Transition
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
        

        [[yourView layer] addAnimation:animation forKey:@"SwitchToView1"];// here you can set any view or any Control For Ex: UITableViewCell

Monday, 17 February 2014

Get Date and Time difference with different format with my custom method

You can get difference with bellow code

   NSString *strDifference = [self getDateDifferencewithTimeDay:yourOldDateString strDate2:[self StringFromDate:[NSDate date]]];
NSLog(@"\n Difference  =====>> %@", strDifference);

 Here i set old string and current string to get difference between that both dates.
Here i use two methods in above code one is getDateDifferencewithTimeDay for get difference between that dates and second is StringFromDate for get data in string format.


-(NSString *)getDateDifferencewithTimeDay:(NSString *)strDate1 strDate2:(NSString *)strDate2{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    NSDate *Date1;
    NSDate *Date2;
    NSString *strAnswer;
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    Date1 = [formatter dateFromString:strDate1];
    Date2 = [formatter dateFromString:strDate2];
    
    NSTimeInterval timeDifference = [Date2 timeIntervalSinceDate:Date1];
    
    double minutes = timeDifference / 60;
    
    double hours = minutes / 60;
    
    double seconds = timeDifference;
    
    double days = minutes / 1440;
    
    if (seconds < 60) {
        strAnswer = [NSString stringWithFormat:@"%.0f Seconds ago.",seconds];
    }
    else if (minutes < 60){
        strAnswer = [NSString stringWithFormat:@"%.0f Minutes ago.",minutes];
    }
    else if (hours < 24){
        strAnswer = [NSString stringWithFormat:@"%.0f Hours ago.",hours];
    }
    else{
        strAnswer = [NSString stringWithFormat:@"%.0f Days ago.",days];
    }
    return strAnswer;
}

And also this bellow method is for convert NSDate to NSString format

-(NSString *)StringFromDate:(NSDate *)DateLocal{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormat stringFromDate:DateLocal];
    NSLog(@"Date is HERE  =====>> %@",dateString);
    return dateString;
}

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