Tuesday, 18 November 2014

How to set separator inset to 0 ( frame of separator) of UITableView ?

Just put this code in your .m class and it will work.

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }

Tuesday, 26 August 2014

Display LoadingView for any Device from AppDelegate on any UIViewController

Here this bellow code is used to display Custom LoadingView on any View whenever you want.
Whenever you call any url or web-service at that time activity indicator or loading view required for display that system in process so user wait for the response.

Here using my bellow code and methods you can easily Apply this code in your projects and easily you can use it in any class.

Here another method is used to get instance of AppDelegate and you can call It's method from any class.

First in AppDelegate.h file just create this bellow objects and methods.

@interface AppDelegate : UIResponder <UIApplicationDelegate>{
    
    UIView *activityView;
    UIView *loadingView;
    UILabel *lblLoad;
    
}

-(void) showLoadingView;
-(void) hideLoadingView;
+(AppDelegate *)sharedInstance;
@end

and in AppDelegate.m class just paste these bellow code...

#pragma  Loading View

-(void) showLoadingView {
    if (loadingView == nil) {
        loadingView = [[UIView alloc] initWithFrame:self.window.frame];
        UIImageView *imgBack = [[UIImageView alloc]initWithFrame:loadingView.frame];
        [loadingView addSubview:imgBack];
        imgBack.opaque = NO;
        imgBack.backgroundColor = [UIColor darkGrayColor];
        imgBack.alpha = 0.5;
        UIView *subloadview=[[UIView alloc] initWithFrame:CGRectMake(84.0, 190.0,150.0 ,50.0)];
        subloadview.backgroundColor=[UIColor blackColor];
        subloadview.opaque=NO;
        subloadview.alpha=0.6;
        subloadview.layer.masksToBounds = YES;
        subloadview.layer.cornerRadius = 6.0;
        lblLoad=[[UILabel alloc]initWithFrame:CGRectMake(50.0, 7.0,80.0, 33.0)];
        lblLoad.text=@"LoadingView";
        lblLoad.backgroundColor=[UIColor clearColor];
        lblLoad.textColor=[UIColor whiteColor];
        [subloadview addSubview:lblLoad];
        UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(10.0, 11.0, 25.0, 25.0)];
        [spinningWheel startAnimating];
        spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        [subloadview addSubview:spinningWheel];
        subloadview.center = loadingView.center;

        [loadingView addSubview:subloadview];
    }
    [self.window addSubview:loadingView];
}

-(void) hideLoadingView {
    if (loadingView) {
        [loadingView removeFromSuperview];
        loadingView = nil;
    }
    
}

+(AppDelegate *)sharedInstance
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}



whenever you want to display loadingview then just use bellow code...

        [[AppDelegate sharedInstance]showLoadingView];

and for this you just need to import AppDelegate.h file in you class where you use above code of showLoadingView like bellow..

#import "AppDelegate.h"


Wednesday, 30 July 2014

How to set view for particular orientation in any view forcefully?



Here using this bellow code you can set any orientation forcefully to any view...


[[UIDevice currentDevice] performSelector:NSSelectorFromString(@"setOrientation:")

                                                                      withObject:(__bridge id)((void*)UIInterfaceOrientationPortrait)];

after put this code you get warning that "PerformSelector may cause a leak because its selector is unknown"

for remove this code you can use this above code with bellow solution...

First define the bellow code in your .m file

#define SuppressPerformSelectorLeakWarning(Stuff) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while (0)

after use that above code with bellow method...

SuppressPerformSelectorLeakWarning(
         [[UIDevice currentDevice] performSelector:NSSelectorFromString(@"setOrientation:")
                                                                      withObject:(__bridge id)((void*)UIInterfaceOrientationPortrait)];
    );

you can use this code in viewDidLoad method or anywhere in which you want to display whole view in particular orientation forcefully

Friday, 25 July 2014

Set All Orientation for only one UIViewController in your whole application.

In AppDelegate class just use this bellow method which is available in iOS 6 and later....

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    // Get topmost/visible view controller
    UIViewController *currentViewController = [self topViewController];// this topViewController is my custom method which i post bellow...

    if ([currentViewController isKindOfClass:[YourClassName class]]) {
            // Unlock landscape view orientations for this view controller
            return UIInterfaceOrientationMaskAllButUpsideDown;
    }
    
    // Only allow portrait (standard behaviour)
    return UIInterfaceOrientationMaskPortrait;
}

This is custom methods which is used to find out top viewController

- (UIViewController*)topViewController {
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }

}

Also For do some changes in your that class in which you want to available different orientation then in that class's use bellow method...

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        NSLog(@"Landscape Orientation Called");
    }
    else{
        NSLog(@"Potrait Orientation Called");
    }
}  

If Any suggestion then please post comment...

Wednesday, 9 July 2014

Set Landscape Oriantation forcefull with bellow code.

    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
    
    float   angle = M_PI/2//rotate 180°, or 1 π radians

    self.view.layer.transform = CATransform3DMakeRotation(angle, 0, 0.0, 1.0);

Thursday, 24 April 2014

Rotate UIView or UIImageView with this bellow code.

 For use this code import QuartzCore framework like bellow

#import <QuartzCore/QuartzCore.h>   

and then use bellow code

   CABasicAnimation *theAnimation;
    theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    theAnimation.duration=1.0; // Animation duration
    theAnimation.repeatCount=1; // no of times you want to do animation
    theAnimation.autoreverses=YES; // reverses the animation
    theAnimation.fromValue=[NSNumber numberWithFloat:0.0]; // initial stage of animation
    theAnimation.toValue=[NSNumber numberWithFloat:3.0]; // rotation angle

    [yourImageView.layer addAnimation:theAnimation forKey:@"animateRotation"]; // add animation to thelayer of a view for which you want animation.

Thursday, 17 April 2014

open mapview with any address name from iphone application to apple map application

with bellow code you can open any location with its name to apple's mapview application with bellow code..


//    [[MKMapItem mapItemForCurrentLocation] openInMapsWithLaunchOptions:nil];// you can open user current location with this 1 line  

    Class mapItemClass = [MKMapItem class];
    if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)])
    {
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder geocodeAddressString:yourAddressText
                     completionHandler:^(NSArray *placemarks, NSError *error) {
                         
                         // Convert the CLPlacemark to an MKPlacemark
                         // Note: There's no error checking for a failed geocode
                         CLPlacemark *geocodedPlacemark = [placemarks objectAtIndex:0];
                         MKPlacemark *placemark = [[MKPlacemark alloc]
                                                   initWithCoordinate:geocodedPlacemark.location.coordinate
                                                   addressDictionary:geocodedPlacemark.addressDictionary];
                         
                         // Create a map item for the geocoded address to pass to Maps app
                         MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
                         [mapItem setName:geocodedPlacemark.name];
                         [mapItem openInMapsWithLaunchOptions:nil];

    }

Load URL in UIWebView with special character , append some string with bellow code.

Here you can add any code or string in your local file url with bellow code.

if your url like user/.../filename.htm and if you want to add some hash code of word after that url like user/.../filename.htm#green then you can use my bellow function.

-(void)loadWebView{
    NSString *path;
NSBundle *thisBundle = [NSBundle mainBundle];
path = [thisBundle pathForResource:@"filename" ofType:@"html"];//here write your file name and its extention
    NSURL *url = [NSURL fileURLWithPath:path];
    NSURL *fullURL = [NSURL URLWithString:@"#green" relativeToURL:url];//pass any code or string with append in url baseurl like this
    [yourWebView loadRequest:[NSURLRequest requestWithURL:fullURL]];
    [yourWebView setBackgroundColor:[UIColor clearColor]];
    [yourWebView setOpaque:NO];

}

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

}