Thursday 12 December 2013

Bounce the UIView vertically using CABasicAnimation


+(void)bounceTheViewVertically:(UIView*)view
{
    CGPoint origin = view.center;
    CGPoint target = CGPointMake(view.center.x, view.center.y-50);
    CABasicAnimation *bounce = [CABasicAnimation animationWithKeyPath:@"position.y"]; //Animations for y axis
    bounce.duration = 0.5;
    bounce.fromValue = [NSNumber numberWithInt:origin.y];
    bounce.toValue = [NSNumber numberWithInt:target.y];
    bounce.repeatCount = 2;
    bounce.autoreverses = YES// undo changes after Animations.
    [view.layer addAnimation: bounce forKey:@"position"];

}

Thursday 5 December 2013

The unique identifier in iOS App. "UDID" is replaced in ios 7 with "identifierForVendor"!

Sometimes in our app we need the unique key for identifying the device or user.

We can use UDID till iOS 6 and identifierForVendor for iOS 7 onwards.

    -(NSString*)uniqueIDForDevice
    {
        NSString* uniqueIdentifier = nil;
        if( [UIDevice instancesRespondToSelector:@selector(identifierForVendor)] ) {
             // >=iOS 7
            uniqueIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        }
        else {  //<=iOS6, Use UDID of Device     
                CFUUIDRef uuid = CFUUIDCreate(NULL);
                //uniqueIdentifier = ( NSString*)CFUUIDCreateString(NULL, uuid);- for non- ARC
                uniqueIdentifier = ( NSString*)CFBridgingRelease(CFUUIDCreateString(NULL, uuid));// for ARC
                CFRelease(uuid);
             }
        }
    return uniqueIdentifier;
    }



Important Note ---

UDID and identifierForVendor are different:---     

  •     1.) On uninstalling  and reinstalling the app identifierForVendor will change.   
  •     2.) The value of identifierForVendor remains the same for all the apps installed from the same vendor on the device.
  •     3.) The value of identifierForVendor also changes for all the apps if any of the app (from same vendor) is reinstalled.

Saturday 30 November 2013

Check whether NSString starts with aplhabet letter only.


+(BOOL)validateFirstCharacterAsAlphabet:(NSString *)str;
{
    NSRange first = [str rangeOfComposedCharacterSequenceAtIndex:0];
    NSRange match = [str rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet] options:0 range:first];
    if (match.location != NSNotFound) {
        // String starts with a letter
        return YES;
    }
    return NO;
    
}

Tuesday 8 October 2013

Copy a UIView from xib and programmatically repeat it using NSKeyedArchiver and NSKeyedUnarchiver.


Lets create a _contactView in .h file using IBOutlet, and connect it in .xib file.
Connect it to the _contactView.

In .m:
//The following line will create a similar view as _contactView in the XIB;
 id copyOfView = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:_contactsView]];



// Repeat the view to generate multiple copies and add to the scroll view.
for (int i =0; i<_contactArray.count; i++) {
        UIView* tempView ;//= [[UIView alloc]init];
        id copyOfView = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:_contactsView]];
        tempView = copyOfView;
        tempView.tag = i;
        [tempView setFrame:CGRectMake(xOffset, yOffset, width, height)];
        yOffset += ySpacing+height;
        [_contactScrollView addSubview:tempView];

    }

    [_contactScrollView setContentSize:CGSizeMake(_contactsView.frame.size.width, _contactsView.frame.size.height*(_contactArray.count+1))];


Open other apps from iOS app using URL scheme. Open google maps, mail from the app, call a number, send sms using Xcode.


Use openURL: function of UIApplication.

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

Open The Google Maps:

// Create string for the place ...
NSString* placeStr = @"1 Infinite Loop, Cupertino, CA 95014";
// Encode URL encode
placeStr =  [addressText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// Now create the URL string ...
NSString* urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@", placeStr];
// use openURL to launch the app ...
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlText]];

Mail from the app:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://info@example.com"]];

Call a number:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://9876543210"]];

Send SMS:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:55555"]];

Open App Store:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/en/app/apple-store/id375380948?mt=8"]];

Wednesday 18 September 2013

Vibrate UIView. Add Shivering effect to the view.


+ (void)vibrateView:(UIView*)view
{
    CABasicAnimation *shiverAnimationR;
    shiverAnimationR = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    shiverAnimationR.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(1)];
    //shiverAnimationR.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(-10)];
    shiverAnimationR.duration = 0.1;
    shiverAnimationR.repeatCount = 1000000.0; // Use A high Value
    shiverAnimationR.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

    [view.layer addAnimation: shiverAnimationR forKey:@"shiverAnimationR"];


    CABasicAnimation * shiverAnimationL;
    shiverAnimationL = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //shiverAnimationL 2.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(10)];
    shiverAnimationL.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(-1)];
    shiverAnimationL.duration = 0.1;
    shiverAnimationL.repeatCount = 1000000.0;
    shiverAnimationL.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

    [view.layer addAnimation: shiverAnimationL forKey:@"shiverAnimationL"];

}

Rotate the UIView clockwise. Rotate or swing UIView in circular manner.




+(void)rotateViewLikeCircle:(UIView*)view rotation:(int)numberOfRotation 
{
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(180)];
    rotationAnimation.duration = 0.75;
    rotationAnimation.repeatCount = numberOfRotation;
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

    [view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

Also don't forget to add the macros for converting degree to radian and visa-versa.

#define DEGREES_TO_RADIANS(degree) (M_PI * degree / 180.0)

#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))


Tuesday 27 August 2013

Check the text Font is "Bold" or "Italic" UIFont.



Import CoreTextFrameWork.

#import <CoreText/CoreText.h>


+(BOOL)isBold
{
    CTFontRef fontRef = (__bridge CTFontRef)self;
    CTFontSymbolicTraits symbolicTraits = CTFontGetSymbolicTraits(fontRef);
    return (symbolicTraits & kCTFontBoldTrait);
}

+(BOOL)isItalic
{
    CTFontRef fontRef = (__bridge CTFontRef)self;
    CTFontSymbolicTraits symbolicTraits = CTFontGetSymbolicTraits(fontRef);
    return (symbolicTraits & kCTFontItalicTrait);
}

Friday 23 August 2013

Git Hub Tutorial. Introduction to commands.

Introduction: 
When working on a project, you need to manage and organize the code. 
Like organize according to User modified a file in the project, or Date and time when you changed the file and many other.
Git keep the track of the files you changed and also allow you to update the code on remote device,and allow your team mates to access the code. Now, they can access the modify code and all other files in more organized way. 
Difference:
The major difference between Git and any other VCS (Subversion and friends included) is the way Git thinks about its data. Conceptually, most other systems store information as a list of file-based changes. These systems (CVS, Subversion, Perforce, Bazaar, and so on) think of the information they keep as a set of files and the changes made to each file over time.

Git doesn’t think of or store its data this way. Instead, Git thinks of its data more like "SAVED STATE", a set of snapshots of a mini filesystem. Every time you commit, or save the state of your project in Git, it basically takes a picture of what all your files look like at that moment and stores a reference to that snapshot.
For Example if a major Bug occurs after the changes then you can go back to a "saved state", start building again from there. Like that you paused a game to a state and then can resume from that point.
To be efficient, if files have not changed, Git doesn’t store the file again—just a link to the previous identical file it has already stored.
      pull 
  <---------------------
    User                                        Remote Repository        
      -----------------------> 
                     push

pull    -   Fetch data from Remote Repository.
push  -   Update the Remote Repository with local changes.


USER 1 USER2
        \ \         / /
          \  \     / /
       Remote Repository        
            / /     \ \                                            
              / /           \ \
        USER n USER3






There are two easy ways to install Git on a Mac. The easiest is to use the graphical Git installer, which you can download from the Google Code page 
http://code.google.com/p/git-osx-installer
The other major way is to install Git via MacPorts (http://www.macports.org). 
If you have MacPorts installed, install Git via
$ sudo port install git-core +svn +doc +bash_completion +gitweb
You don’t have to add all the extras, but you’ll probably want to include +svn in case you ever have to use Git with Subversion repositories



Lets Begin:
Press "cmd" + space"
Type : "terminal" in spotlight.
It will open a terminal window. 

Browse to folder where you want to store the project locally. You can "cd" command to navigate in in your folders.
cd Users/HD/Desktop/Git/
It will take to the folder Git.

You clone a repository with git clone [url]. For example, if you want to clone the Ruby Git library called Grit, you can do so like this:
$ git clone git://github.com/HD/grit.git


The main tool you use to determine which files are in which state is the git status command. If you run this command directly after a clone, you should see something like this:
$ git status


In order to begin tracking a new file, you use the command git add. To begin tracking the READMEfile, you can run this:
$ git add README

Now that your staging area is set up the way you want it, you can commit your changes. Remember that anything that is still unstaged — any files you have created or modified that you haven’t rungit add on since you edited them — won’t go into this commit. They will stay as modified files on your disk. In this case, the last time you ran git status, you saw that everything was staged, so you’re ready to commit your changes. The simplest way to commit is to type git commit:
You can type your commit message inline with the commit command by specifying it after a -m flag, like this:
$ git commit -m "Eg: This is custom msg related to commit"




Pushing Remotely
The push command tells Git where to put our commits when we're ready, and boy we're ready. So let's push our local changes to our origin repo (on GitHub).
The name of our remote is origin and the default local branch name is master. The -u tells Git to remember the parameters, so that next time we can simply run git push and Git will know what to do. Go ahead and push it! 
$ git push -u origin master





eBook:
Tuts:

Monday 12 August 2013

Show Hide the side content view with UIButton click.


We need to display a help menu or content of book which scrolls up on the view and show new view to the user.

Declare a BOOL to check view is hidden or not.
In .h
BOOL _isContentVisible
UIView *_sideContentView;
-(IBAction)showHideContentView:(id)sender;
In .Xib
Connect the showHideContentView function to UIButton touchUpInside action.
In .m
-(void)showHideContentView:(id)sender
{
    //BOOL isContentVisible= CGRectIntersectsRect(self.view.bounds, _sideContentScrollView.frame); // you can check view visibility if its scrollview.

    [UIView animateWithDuration:1.0f
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         //hide if visible else show

                         if (_isContentVisible) { // Hide
                             _isContentVisible = NO;
                             [_sideContentView setFrame:CGRectMake(-360 +40, 0, 360, 748)];// 40 pixels is button to be seen on the view. Set the frame according to your choice.

                         }
                         else { // Show
                             _isContentVisible = YES;
                             [_sideContentView setFrame:CGRectMake(0, 0, 360, 748)];
                         }
                     }
                     completion:^(BOOL finished) {
                         if (finished) {
                          // Do any custom stuff on completion.
                         }
                     }];
}

Tuesday 6 August 2013

Check that string contains only numeric values (number 0-9).


+(BOOL) validateStringContainsNumbersOnly:(NSString*)strng
{
    NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"1234567890"];

    s = [s invertedSet];
    //And you can then use a string method to find if your string contains anything in the inverted set:

    NSRange r = [strng rangeOfCharacterFromSet:s];
    if (r.location != NSNotFound) {
        NSLog(@"the string contains illegal characters");
        return NO;
    }
    else
        return YES;
}

Check if string contains only alphabets. Using NSString, NSCharacterSet, NSRange.


+(BOOL) validateStringContainsAlphabetsOnly:(NSString*)strng
{
    NSCharacterSet *strCharSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];//1234567890_"];

    strCharSet = [strCharSet invertedSet];
    //And you can then use a string method to find if your string contains anything in the inverted set:

        NSRange r = [strng rangeOfCharacterFromSet:strCharSet];
    if (r.location != NSNotFound) {
        NSLog(@"the string contains illegal characters");
        return NO;
    }
    else
        return YES;
}

Sunday 4 August 2013

Find number of days between two dates.


+ (int)daysBetweenFromDate:(NSDate*)fromDateTime toDate:(NSDate*)toDateTime
{
    NSDate *fromDate;
    NSDate *toDate;

    //initialize the calender
    NSCalendar *calendar = [NSCalendar currentCalendar];

    //Returns by reference the starting time and duration of a given calendar unit that contains a given date.
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate
                 interval:NULL forDate:fromDateTime];
    
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate
                 interval:NULL forDate:toDateTime];

    //Returns, as an NSDateComponents object using specified components, the difference between two supplied dates.
    NSDateComponents *difference = [calendar components:NSDayCalendarUnit
                                               fromDate:fromDate toDate:toDate options:0];
    
    return [difference day];
}

Saturday 27 July 2013

NSDate from NSString. Fetch Date from string.

+(NSDate*)dateFromString:(NSString*)dateStr
{
    // Choose your format according to date string
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"LLLL d,YYYY"];
    NSDate *date = [dateFormat dateFromString:dateStr];
    NSLog(@"String:%@ convert to date:%@",dateStr, date.description);

    return date;
    
}

Friday 19 July 2013

Check view controller is visible or not. UIViewController and UINavigationController


if (viewController.isViewLoaded && viewController.view.window)
    // viewController is visible
 else  // viewController is not visible


UIViewController


1.) isViewLoaded

Returns a Boolean value indicating whether the view is currently loaded into memory.
- (BOOL)isViewLoaded
Return Value
A Boolean value indicating whether the view is currently loaded into memory.
Discussion
Calling this method reports whether the view is loaded. Unlike the view property, it does not attempt to load the view if it is not already in memory.

2.) viewController.view.window

If  view  is currently visible the its window property is non-nil. So we check viewController.view.window.
Calling the view method loads the view(if not yet loaded), so we call isViewLoaded before it.

UINavigationController 


In UINavigationController we can use its visibleViewController property.

visibleViewController

The view controller associated with the currently visible view in the navigation interface. (read-only)
@property(nonatomic, readonly, retain) UIViewController *visibleViewController
Discussion
The currently visible view can belong either to the view controller at the top of the navigation stack or to a view controller that was presented modally.
We can compare this with our viewController and find whether its visible or not.

Tuesday 16 July 2013

UILabel top aligned. Align text to top left. The text is displayed in the vertical center of the label? NSTextAlignment.


 UILabel if text in label is too short to fit in the number of lines used for that label, the text is displayed in the vertical center of the label.






To vertically align the text at the top of the UILabel

    _titleLabel.text = [self._myArray objectAtIndex:indexPath.row]; // get text array.


    [_titleLabel setNumberOfLines:0]; 
    // 


    [_titleLabel sizeToFit];