Pages

Subscribe:

Wednesday, November 23, 2011

How to retrieve device's IP Address programmatically

// Add these header files in your *.m file
#include "ifaddrs.h"
#include "arpa/inet.h"


// Add this function in your *.m file
- (NSString *)getIPAddress {

NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

}

}

temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;

}

Monday, October 10, 2011

More sensitive or responsive custom UISlider





Normally a slider contains a limited area to detect the touch & act on that. Default height of a
slider is 23 pixels, in which the thumb contains only 19 pixels area to get the touch.


Sometimes we need to use a slider which should act more smooth & responsive just like the native "Slide to unlock" button of iPhone. So, for that, we need to increase the area of touch of a slider.


To make a slider with increased touch area, at first you need to make a subclass of UISlider, such as MySlider.

So MySlider.h file will look like this:

#import

@interface MySliderClass : UISlider {

}

@end


MySlider.m file will look like this:

#import "MySliderClass.h"

/* How many extra touchable pixels you want above and below
the 23px (default height) slider */

#define SIZE_EXTENSION_Y -10 // Adjust this value as required in your project

// Define another value if you want to extend size in x-axis

@implementation MySliderClass

- (BOOL) pointInside:(CGPoint)point withEvent:(UIEvent*)event {

NSLog(@"pointSide");

CGRect bounds = self.bounds;

bounds = CGRectInset(bounds, 0, SIZE_EXTENSION_Y);

return CGRectContainsPoint(bounds, point);

}

@end

Now in your interface builder, set the slider to use your new MySlider subclass, and you now have a slider with a 43px touchable height.

Thursday, September 22, 2011

Telephone Number validation in a UITextField

// First you need to implement the UITextFieldDelegate in the .h file
// This validation will test, whether the number started with a '+' character or not & the number is not more than 19 digits.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *invalidCharSet;
if(textField == txtTelephoneNumber)
{
invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@" +0123456789"] invertedSet];
if([textField.text length] < 1)
{
if ([string characterAtIndex:0] != '+')
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"You must enter a valid telephone number. (Example: +8801913952792 ...)" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
}
}
else
{
if ([textField.text characterAtIndex:0] != '+') {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"You must enter a valid telephone number. (Example: +01913952792 ...)" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
}
}
if([textField.text length] > 19 && range.length == 0)
return NO;
}
else
{
invalidCharSet = [NSCharacterSet characterSetWithCharactersInString:@""];
//return [self validateEmail:string];
//invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@""] invertedSet];
}

NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];

if(![string isEqualToString:filtered])
return NO;
else
return YES;
}

Email address validation in a text field

// This function will return either TRUE or FALSE depending on the validity of a given email address
-(BOOL) validateEmail: (NSString *) candidate {
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:candidate];
}

// Implement the UITextFieldDelegate in the .h file
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if(textField == txtEmail)
{
if([self validateEmail:textField.text])
[textField resignFirstResponder];
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Please enter a valid email address." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
}
}
return YES;
}

Tuesday, July 19, 2011

How to make a slider button just like iPhone's native Unlock Button


/* In the above screen shot, i've used the UISlider as a alarm triggering object. (as required in an application) */

/* Use your custom images as your requirements. Declare required variables & objects in *.h file. You will need a UIImageView, a UILabel, a UIButton & a UISlider in your NIB file and locate them to desired name.*/

- (void)viewDidLoad {
[super viewDidLoad];
// initialize custom UISlider (you have to do this in viewdidload or applicationdidfinishlaunching.
UIImage *stetchLeftTrack= [[UIImage imageNamed:@"Nothing.png"]
stretchableImageWithLeftCapWidth:30.0 topCapHeight:0.0];
UIImage *stetchRightTrack= [[UIImage imageNamed:@"Nothing.png"]
stretchableImageWithLeftCapWidth:30.0 topCapHeight:0.0];
[mySlider setThumbImage: [UIImage imageNamed:@"SlideToStop.png"] forState:UIControlStateNormal];
[mySlider setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
[mySlider setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];

}


-(IBAction)LockIt
{
mySlider.hidden = NO;
lockButton.hidden = YES;
Container.hidden = NO;
myLabel.hidden = NO;
myLabel.alpha = 1.0;
UNLOCKED = NO;
mySlider.value = 0.0;
NSString *str = @"The iPhone is Locked!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Locked" message:str delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
}

-(IBAction)fadeLabel
{
myLabel.alpha = 1.0 - mySlider.value;
}

-(IBAction)UnLockIt
{
if (!UNLOCKED)
{
if (mySlider.value == 1.0)
{ // if user slide far enough, stop the operation
// Put here what happens when it is unlocked

mySlider.hidden = YES;
lockButton.hidden = NO;
Container.hidden = YES;
myLabel.hidden = YES;
UNLOCKED = YES;
}
else
{
// user did not slide far enough, so return back to 0 position
[UIView beginAnimations: @"SlideCanceled" context: nil];
[UIView setAnimationDelegate: self];
[UIView setAnimationDuration: 0.35];
// use CurveEaseOut to create "spring" effect
[UIView setAnimationCurve: UIViewAnimationCurveEaseOut];
mySlider.value = 0.0;
[UIView commitAnimations];

/* if u don't want to use custom animation with desired duration then u can use the following line :

[mySlider setValue:0.0 animated:YES];
*/

}
}
}

Friday, July 15, 2011

Accessing & playing iPod's music player through application

- (void)viewDidLoad {
[super viewDidLoad];

mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeAny];
mediaPicker.delegate = self;
mediaPicker.allowsPickingMultipleItems = YES;
mediaPicker.editing = YES;

[self musicPlayerInitialize];

}

-(void)musicPlayerInitialize
{
myPlayer = [MPMusicPlayerController iPodMusicPlayer];

[myPlayer setQueueWithQuery: [MPMediaQuery songsQuery]];
[myPlayer setRepeatMode:MPMusicRepeatModeAll];

[myPlayer beginGeneratingPlaybackNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(changeTitle)
name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object:myPlayer];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleExternalVolumeChanged:)
name:MPMusicPlayerControllerVolumeDidChangeNotification
object:myPlayer];


}


-(void)changeTitle
{
MPMediaItem *item = [myPlayer nowPlayingItem];
NSString *titleStr = [item valueForProperty:MPMediaItemPropertyTitle];
lblSongTitle.text = titleStr;
NSLog(@"Now Playing Song Name: %@",titleStr);
}


-(IBAction)playButtonPressed
{
if(myPlayer.playbackState == MPMusicPlaybackStatePaused || myPlayer.playbackState == MPMusicPlaybackStateStopped)
{
[myPlayer play];
[btnMusicPlay setImage:[UIImage imageNamed:@"pause_btn.png"] forState:UIControlStateNormal];
}
else if(myPlayer.playbackState == MPMusicPlaybackStatePlaying)
{
[myPlayer pause];
[btnMusicPlay setImage:[UIImage imageNamed:@"play_btn.png"] forState:UIControlStateNormal];
}
[self changeTitle];
}

-(IBAction)nextButtonPressed
{
[myPlayer skipToNextItem];
[self changeTitle];
}

-(IBAction)prevButtonPressed
{
[myPlayer skipToPreviousItem];
[self changeTitle];
}

-(IBAction)volumeChange:(id)sender
{
[[NSUserDefaults standardUserDefaults] setFloat:myVolumeSlider.value forKey:@"musicVolume"];
myPlayer.volume = myVolumeSlider.value;
NSLog(@"volume changing: %f",myVolumeSlider.value);
}

- (void)handleExternalVolumeChanged:(id)notification {
// self.volumeSlider is a UISlider used to display music volume.
// self.musicPlayer.volume ranges from 0.0 to 1.0.
[myVolumeSlider setValue:myPlayer.volume animated:YES];
}


# pragma mark -
# pragma mark media picker Delegate

-(void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker
{
[self dismissModalViewControllerAnimated:YES];
}

-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:mediaItemCollection];

MPMediaItemCollection *tempMediaItem = [tempArray objectAtIndex:0];
[appDelegate.myPlayer setQueueWithItemCollection:tempMediaItem];
[appDelegate.myPlayer play];
[self dismissModalViewControllerAnimated:YES];
}

-(IBAction)playlistButtonPressed
{
[self presentModalViewController:mediaPicker animated:YES];
}

Countdown Timer with remaining time & custom label (hr:min:sec)

-(IBAction)timerStartButtonPressed
{
if(!isStarted)
{
isStarted = TRUE;
isPaused = FALSE;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFunction:) userInfo:nil repeats:YES];
}
}

-(IBAction)timerPauseButtonPressed
{
if(!isPaused)
{
isStarted = FALSE;
isPaused = TRUE;
[timer invalidate];
}
}



-(void)timerFunction:(NSTimer *)theTimer
{
second = second-1;
remSecond = remSecond + 1;

if(hour >= 0)
{
if (second < 0)
minute = minute-1;

if(remSecond > 59)
remMinute = remMinute + 1;

if(minute < 0)
hour = hour - 1;

if(remMinute > 59)
remHour = remHour + 1;

if(minute < 0 && second < 0 && hour < 0)
{
strSecond = @"00";
strMinute = @"00";
strHour = @"00";

NSString *tempTestDuration = [[NSUserDefaults standardUserDefaults] valueForKey:@"restDuration"];
NSArray *tempArray = [tempTestDuration componentsSeparatedByString:@":"];

remHour = [[tempArray objectAtIndex:0] intValue];
remMinute = [[tempArray objectAtIndex:1] intValue];
remSecond = [[tempArray objectAtIndex:2] intValue];


isStarted = FALSE;
isPaused = TRUE;

[timer invalidate];
timer = nil;

if(isTestRunning && remainingSet < totalSet)
{
[self resetRest];
[self timerStartButtonPressed];
}
else if(!isTestRunning && remainingSet < totalSet)
{
[self resetTest];
if([[NSUserDefaults standardUserDefaults] boolForKey:@"isNewSongInEachTestOn"] == YES)
[appDelegate.myPlayer skipToNextItem];
[self timerStartButtonPressed];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Finish!!!" message:@"Time up." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}

return;
}

if (second>=0)
{
if (second<10)
strSecond = [NSString stringWithFormat:@"0%d", second];
else
strSecond = [NSString stringWithFormat:@"%d", second];
}
else
{
second=59;
strSecond = [NSString stringWithFormat:@"%d", second];
}

if(remSecond <= 59)
{
if (remSecond<10)
strRemSecond = [NSString stringWithFormat:@"0%d", remSecond];
else
strRemSecond = [NSString stringWithFormat:@"%d", remSecond];
}
else
{
remSecond=0;
strRemSecond = [NSString stringWithFormat:@"0%d", remSecond];
}

if(minute >= 0)
{
if (minute<10)
strMinute = [NSString stringWithFormat:@"0%d", minute];
else
strMinute = [NSString stringWithFormat:@"%d", minute];
}
else
{
minute = 59;
strMinute = [NSString stringWithFormat:@"%d",minute];
}

if(remMinute <= 59)
{
if (remMinute<10)
strRemMinute = [NSString stringWithFormat:@"0%d", remMinute];
else
strRemMinute = [NSString stringWithFormat:@"%d", remMinute];
}
else
{
minute = 0;
strMinute = [NSString stringWithFormat:@"0%d",remMinute];
}


if (hour<10)
strHour = [NSString stringWithFormat:@"0%d", hour];
else
strHour= [NSString stringWithFormat:@"%d", hour];

if (remHour<10)
strRemHour = [NSString stringWithFormat:@"0%d", remHour];
else
strRemHour= [NSString stringWithFormat:@"%d", remHour];

NSString *tempStr = [NSString stringWithFormat:@"%@:%@:%@",strHour,strMinute,strSecond];
NSString *tempStrRem = [NSString stringWithFormat:@"%@:%@:%@",strRemHour,strRemMinute,strRemSecond];
NSLog(@"tempStr: %@",tempStr);

if([tempStr characterAtIndex:0] == '0')
{
strHour = [NSString stringWithFormat:@"%c",[tempStr characterAtIndex:1]];
tempStr = [NSString stringWithFormat:@"%@:%@:%@",strHour,strMinute,strSecond];
NSLog(@"tempStr: %@",tempStr);

if([tempStr characterAtIndex:0] == '0')
{
tempStr = [NSString stringWithFormat:@"%@:%@",strMinute,strSecond];
NSLog(@"tempStr: %@",tempStr);

if([tempStr characterAtIndex:0] == '0')
{
strMinute = [NSString stringWithFormat:@"%c",[tempStr characterAtIndex:1]];
tempStr = [NSString stringWithFormat:@"%@:%@",strMinute,strSecond];
NSLog(@"tempStr: %@",tempStr);

if([tempStr characterAtIndex:0] == '0')
{
tempStr = [NSString stringWithFormat:@"0:%@",strSecond];
NSLog(@"tempStr: %@",tempStr);
}
}
}
}

if([tempStrRem characterAtIndex:0] == '0')
{
strRemHour = [NSString stringWithFormat:@"%c",[tempStrRem characterAtIndex:1]];
tempStrRem = [NSString stringWithFormat:@"%@:%@:%@",strRemHour,strRemMinute,strRemSecond];
NSLog(@"tempStr: %@",tempStrRem);

if([tempStrRem characterAtIndex:0] == '0')
{
tempStrRem = [NSString stringWithFormat:@"%@:%@",strRemMinute,strRemSecond];
NSLog(@"tempStr: %@",tempStrRem);

if([tempStrRem characterAtIndex:0] == '0')
{
strRemMinute = [NSString stringWithFormat:@"%c",[tempStrRem characterAtIndex:1]];
tempStrRem = [NSString stringWithFormat:@"%@:%@",strRemMinute,strRemSecond];
NSLog(@"tempStr: %@",tempStrRem);

if([tempStrRem characterAtIndex:0] == '0')
{
tempStrRem = [NSString stringWithFormat:@"0:%@",strRemSecond];
NSLog(@"tempStr: %@",tempStrRem);
}
}
}
}


lblTimerDisplay.text = tempStr;
lblRemainingTimeDisplay.text = [NSString stringWithFormat:@"Elapsed Time %@",tempStrRem];
}
else
{
strSecond = @"00";
strMinute = @"00";
strHour = @"00";

[timer invalidate];
}

}

Tuesday, February 8, 2011

Using image & text together or custom view in a UIPickerView

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {

UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
customButton.frame=CGRectMake(5,5, 50, 50);
UIImage *anImage=[UIImage imageNamed:yourImage];
[customButton setImage:anImage forState:UIControlStateNormal];

UILabel *lblTemp = [[UILabel alloc] initWithFrame:CGRectMake(60, 5, 400, 50)];
lblTemp.text = [NSString stringWithFormat:yourText];

UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 460, 60)];
[tempView addSubview:lblTemp];
[tempView addSubview:customButton];
[view addSubview:tempView];

[lblTemp release];
[tempView release];

return tempView;
}

Wednesday, February 2, 2011

Scaling & Rotating UIImageView through 2 finger swipe

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

NSArray *allTouches = [touches allObjects];

UITouch* t;
if([[event allTouches] count]==1){
if (CGRectContainsPoint([smallImage frame], [[allTouches objectAtIndex:0] locationInView:self.view])) {
t=[[[event allTouches] allObjects] objectAtIndex:0];
touch1=[t locationInView:nil];
}
}else{
t=[[[event allTouches] allObjects] objectAtIndex:0];
touch1=[t locationInView:nil];
t=[[[event allTouches] allObjects] objectAtIndex:1];
touch2=[t locationInView:nil];
}
}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

CGPoint currentTouch1;
CGPoint currentTouch2;
NSArray *allTouches = [touches allObjects];
UITouch* t;
float scale,rotation;

if([[event allTouches] count]==1){
t=[[[event allTouches] allObjects] objectAtIndex:0];
if (CGRectContainsPoint([smallImage frame], [[allTouches objectAtIndex:0] locationInView:self.view]))
{
touch2=[t locationInView:nil];
smallImage.center=CGPointMake(smallImage.center.x+touch2.x-touch1.x,smallImage.center.y+touch2.y-touch1.y);
touch1=touch2;
}
}
else if([[event allTouches] count]==2)
{
t=[[[event allTouches] allObjects] objectAtIndex:0];
currentTouch1=[t locationInView:nil];

t=[[[event allTouches] allObjects] objectAtIndex:1];
currentTouch2=[t locationInView:nil];


scale = [self distance:currentTouch1 toPoint:currentTouch2] / [self distance:touch1 toPoint:touch2];
rotation=atan2(currentTouch2.y-currentTouch1.y, currentTouch2.x-currentTouch1.x)-atan2(touch2.y-touch1.y,touch2.x-touch1.x);
if(isnan(scale)){
scale=1.0f;
}
NSLog(@"rotation %f",rotation);

NSLog(@"scale %f",scale);

if (CGRectContainsPoint([smallImage frame], [[allTouches objectAtIndex:0] locationInView:self.view]) &&
CGRectContainsPoint([smallImage frame], [[allTouches objectAtIndex:1] locationInView:self.view]))
{

smallImage.transform=CGAffineTransformScale(smallImage.transform, scale,scale);
smallImage.transform=CGAffineTransformRotate(smallImage.transform, rotation);
}
else // In case of scaling or rotating the background imageView
{
imageView.transform=CGAffineTransformScale(imageView.transform, scale,scale);
imageView.transform=CGAffineTransformRotate(imageView.transform, rotation);
}

touch1=currentTouch1;
touch2=currentTouch2;
}
}

-(double)distance:(CGPoint)point1 toPoint:(CGPoint)point2
{
return sqrt(fabs(point1.x - point2.x) + fabs(point1.y - point2.y));
}

Tuesday, January 11, 2011

Creating a custom alert

//Background of AlertView is an image And you can change this image

UIAlertView *theAlert = [[[UIAlertView alloc] initWithTitle:@"Your Title"
message: @"Your Message Here"
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];

[theAlert show];

UILabel *theTitle = [theAlert valueForKey:@"_titleLabel"];
[theTitle setTextColor:[UIColor redColor]];

UILabel *theBody = [theAlert valueForKey:@"_bodyTextLabel"];
[theBody setTextColor:[UIColor blueColor]];

UIImage *theImage = [UIImage imageNamed:@"Background.png"];
theImage = [theImage stretchableImageWithLeftCapWidth:16 topCapHeight:16];
CGSize theSize = [theAlert frame].size;

UIGraphicsBeginImageContext(theSize);
[theImage drawInRect:CGRectMake(0, 0, theSize.width, theSize.height)];
theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[[theAlert layer] setContents:[theImage CGImage]];

Friday, January 7, 2011

validating & limit the character length of a TextField

*** This is a delegate method for UITextField


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];

if (textField.text.length >= MAX_LENGTH && range.length == 0)
{
return NO; // return NO to not change text
}
else
{
if(![string isEqualToString:filtered])
return NO;
else
return YES;
}
}

Wednesday, January 5, 2011

Using a custom image button in a navigation bar

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"myImage.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(blah) forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 32, 32)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

***the title of the nav controller will be auto resized this way. If you do it your way (subview of the nav bar) the text will go behind or ontop of the image

***it will also stay on the screen as you pop and push view controllers.

***once again, you can use an imageview as the custom view and not the button. Here is code:


UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,32,32)];
[iv setImage:[UIImage imageNamed:@"myImage.png"]];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:iv];
[iv release];

Vibrate iPhone device through application

-(void)vibrate
{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

Vibrate iPhone device through application

-(void)vibrate
{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

Jerking Effects with an ImageView in y-axis

-(void)shakeImageInY
{
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
anim.values = [NSArray arrayWithObjects:[NSNumber numberWithFloat:-15],
[NSNumber numberWithFloat:15],
nil];
anim.duration = 0.2;
anim.autoreverses = YES;

anim.repeatCount = 0;
anim.additive = YES;
anim.fillMode=kCAFillModeForwards;
[imageView.layer addAnimation:anim forKey:@"wiggleTranslationY"];
}

Jerking Effects with an ImageView in x-axis

-(void)shakeImageInX
{
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
anim.values = [NSArray arrayWithObjects:[NSNumber numberWithFloat:-15],
[NSNumber numberWithFloat:15],
nil];
anim.duration = 0.2;
anim.autoreverses = YES;

anim.repeatCount = 0;
anim.additive = YES;
anim.fillMode=kCAFillModeForwards;
[imageView.layer addAnimation:anim forKey:@"wiggleTranslationY"];
}