Pages

Subscribe:

Featured Posts

Friday, September 7, 2012

How to integrate new Facebook SDK in an iOS application (Basic log in functionality)

New Facebook SDK in iOS is a great built-in feature for the iOS apps developer.

Add this Framework header in your AppDelegate.h file (don't forget to add the Facebook framework).
#import "FacebookSDK/FacebookSDK.h" // Please replace the double quote (") with ('<' and '>')

Add this line to your AppDelegate.h file

extern NSString *const FBSessionStateChangedNotification;

Add this method declaration in your AppDelegate.h file

- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI;

Add these codes in your AppDelegate.m file

NSString *const FBSessionStateChangedNotification =
@"com.yourCompany.yourAppName:FBSessionStateChangedNotification";

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    NSLog(@"url: %@",url);
    return [FBSession.activeSession handleOpenURL:url];
}


/*
 * Callback for session changes.
 */
- (void)sessionStateChanged:(FBSession *)session
                      state:(FBSessionState) state
                      error:(NSError *)error
{
    switch (state) {
        case FBSessionStateOpen:
            if (!error) {
                // We have a valid session
                NSLog(@"User session found");
            }
            break;
        case FBSessionStateClosed:
        case FBSessionStateClosedLoginFailed:
            [FBSession.activeSession closeAndClearTokenInformation];
            break;
        default:
            break;
    }
   
    [[NSNotificationCenter defaultCenter]
     postNotificationName:FBSessionStateChangedNotification
     object:session];
   
    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"Error"
                                  message:error.localizedDescription
                                  delegate:nil
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
        [alertView show];
    }
}

/*
 * Opens a Facebook session and optionally shows the login UX.
 */
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
    return [FBSession openActiveSessionWithPermissions:permissions
                                          allowLoginUI:allowLoginUI
                                     completionHandler:^(FBSession *session,
                                                         FBSessionState state,
                                                         NSError *error) {
                                         [self sessionStateChanged:session
                                                             state:state
                                                             error:error];
                                     }];
}









// Add the following code inside applicationDidBecomeActive: method


if (FBSession.activeSession.state == FBSessionStateCreatedOpening) {   
        [FBSession.activeSession close]; // so we close our session and start over 
    }

// Now it's time to work on your view controller. Add the following observer inside the viewDidLoad: method of your view controller, where you want to share something:

[[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(sessionStateChanged:)
     name:FBSessionStateChangedNotification
     object:nil];

// Here is the call back method for the notification observer
- (void)sessionStateChanged:(NSNotification*)notification {
    if (FBSession.activeSession.isOpen) {
        //[self.authButton setTitle:@"Logout" forState:UIControlStateNormal];
        NSLog(@"State Open");
       
      
        }
        else {
        //[self.authButton setTitle:@"Login" forState:UIControlStateNormal];
        NSLog(@"State Closed");
    }
}


// Here is your facebook button's action:

-(IBAction)facebookButtonPressed
{
    // you need to create the instance for your AppDelegate
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    [appDelegate openSessionWithAllowLoginUI:YES];
}

*** If you want to login into your application with facebook login, you need to create an application at developer.facebook.com/apps

*** Will post more functionality (post image, status, link, etc) later

Thursday, January 26, 2012

How to make a Customized TabBarController with images

First Add a UITabBarController in your storyboard or main window. Then give it a reference from your AppDelegate and override this with a custom tab bar controller class.

Below is a sample screen with a custom tab bar controller:

Here, Contacts, Activity, Chat & History are the 4 tabs where Chat tab is currently selected.

There is an example of a custom class for a UITabBarController with a backgroun image and 3 buttons with custom action & image.

This is the custom tab bar controller class can be look like:

// CustomTabBarController.h

#import 

@interface CustomTabBarController : UITabBarController {
UIButton *settingsButton;
UIButton *infoButton;
UIButton *aboutUsButton;
}

@property (nonatomic, retain) UIButton *settingsButton;
@property (nonatomic, retain) UIButton *infoButton;
@property (nonatomic, retain) UIButton *aboutUsButton;

-(void) addCustomElements;
-(void) selectTab:(int)tabID;

@end

// CustomTabBarController.m

#import "CustomTabBarController.h"

@implementation CustomTabBarController

@synthesize settingsButton, infoButton, aboutUsButton;

- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];


}
-(void)viewDidLoad
{
[super viewDidLoad];
[self addCustomElements];
}

-(void)addCustomElements
{
// Background
UIImageView* bgView = [[[UIImageView alloc] initWithImage:
[
UIImage imageNamed:@"tabBarBackground.png"]] autorelease];
bgView
.frame = CGRectMake(0, 420, 320, 60);
[self.view addSubview:bgView];

// Initialise our two images
UIImage *btnImage = [UIImage imageNamed:@"settings.png"];
UIImage *btnImageSelected = [UIImage imageNamed:
@
"settingsSelected.png"];

//Setup the button
self.settingsButton = [UIButton buttonWithType:UIButtonTypeCustom];

// Set the frame (size and position) of the button)
settingsButton.frame = CGRectMake(10, 426, 100, 54);

// Set the image for the normal state of the button

[settingsButton setBackgroundImage:btnImage forState:
UIControlStateNormal];

// Set the image for the highlighted state of the button
[settingsButton setBackgroundImage:btnImageSelected forState:
UIControlStateHighlighted
];

// Set the image for the selected state of the button
[settingsButton setBackgroundImage:btnImageSelected forState:
UIControlStateSelected
];

// Set the image for the disabled state of the button
[settingsButton setBackgroundImage:btnImageSelected forState:
UIControlStateDisabled];

[settingsButton setImage:btnImageSelected forState:
(
UIControlStateHighlighted|UIControlStateSelected)];

/* Assign the button a "tag" so when our "click" event is called
we know which button was pressed.
*/
[settingsButton setTag:101];

// Set this button as selected (we will select the others to false
as we only want Tab 1 to be selected initially).
*/
[settingsButton setSelected:true];


// Now we repeat the process for the other buttons
btnImage
= [UIImage imageNamed:@"info.png"];
btnImageSelected
= [UIImage imageNamed:@"infoSelected.png"];
self.infoButton = [UIButton buttonWithType:UIButtonTypeCustom];
infoButton
.frame = CGRectMake(110, 426, 100, 54);
[infoButton setBackgroundImage:btnImage forState:
UIControlStateNormal];
[infoButton setBackgroundImage:btnImageSelected forState:
UIControlStateSelected];
[infoButton setBackgroundImage:btnImageSelected forState:
UIControlStateHighlighted
];
[infoButton setImage:btnImageSelected forState:
(
UIControlStateHighlighted|UIControlStateSelected)];
[infoButton setTag:102];


btnImage
= [UIImage imageNamed:@"aboutUs.png"];
btnImageSelected
= [UIImage imageNamed:@"aboutUsSelected.png"];
self.aboutUsButton = [UIButton buttonWithType:UIButtonTypeCustom];
aboutUsButton
.frame = CGRectMake(210, 426, 100, 54);
[aboutUsButton setBackgroundImage:btnImage forState:
UIControlStateNormal
];
[aboutUsButton setBackgroundImage:btnImageSelected forState:
UIControlStateSelected
];
[aboutUsButton setBackgroundImage:btnImageSelected forState:
UIControlStateHighlighted
];
[aboutUsButton setImage:btnImageSelected forState:
(
UIControlStateHighlighted|UIControlStateSelected)];
[aboutUsButton setTag:103];


// Add my new buttons to the view
[self.view addSubview:settingsButton];
[self.view addSubview:infoButton];
[self.view addSubview:aboutUsButton];


/* Setup event handlers so that the buttonClicked method will
respond to the touch up inside event.
*/
[settingsButton addTarget:self action:@selector(buttonClicked:)
forControlEvents
:UIControlEventTouchUpInside];
[infoButton addTarget:self action:@selector(buttonClicked:)
forControlEvents
:UIControlEventTouchUpInside];
[aboutUsButton addTarget:self action:@selector(buttonClicked:)
forControlEvents
:UIControlEventTouchUpInside];
}

- (void)buttonClicked:(id)sender
{
int tagNum = [sender tag];
[self selectTab:tagNum];
}

- (void)selectTab:(int)tabID
{
switch(tabID)
{
case 101:
[settingsButton setSelected:true];
[infoButton setSelected:false];
[aboutUsButton setSelected:false];
break;
case 102:
[settingsButton setSelected:false];
[infoButton setSelected:true];
[aboutUsButton setSelected:false];
break;
case 103:
[settingsButton setSelected:false];
[infoButton setSelected:false];
[aboutUsButton setSelected:true];
break;
}
self.selectedIndex = tabID;
}

- (void)dealloc {
[settingsButton release];
[infoButton release];
[aboutUsButton release];

[super dealloc];
}

@end

Thursday, January 5, 2012

How to send In-app SMS through iOS application

/* This feature is available in iOS 4 or later */

Step 1:

Import the MessageUI Framework into your project and #import the header file into the “.h” file of your controller where you want to open the In-App SMS sheet.

Step 2:

You might already have a button handler IBAction where you want to send the SMS. If not create a Button on your XIB file and write IBActions for it.

Step 3:

The real code

-(IBAction) sendInAppSMS:(id) sender
{
MFMessageComposeViewController *controller =
[
[[MFMessageComposeViewController alloc] init] autorelease];

if
([MFMessageComposeViewController canSendText])
{
controller.body = @"Hello from Erfan";
controller.recipients = [NSArray arrayWithObjects:
@
"12345678", @"87654321", nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}

The most important part here is the line [MFMessageComposeViewController canSendText].
When sending a in-app email, you can choose to ignore this (atleast as of now) because most of the devices would have upgraded to iPhone OS 3 and all those devices would have the ability to send in-app email. However, the same doesn’t apply to SMS. Remember that even if a device is running iPhone OS 4, if it’s an iPod touch, it will never be abel to send SMS within app.
In this case, You have to use an if condition to send the SMS. Practically speaking, you should enable/disable the button the user taps to send the sms based on this. You can add the code that does this in your viewDidLoad method.

Step 4:

Implement Delegate Callbacks.
In your header file, implement the callbacks, MFMessageComposeViewControllerDelegate and UINavigationControllerDelegate. If you don’t you will get a warning at the line,

 controller.delegate = self;

You have to handle a callback method of MFMessageComposeViewControllerDelegate so as to dismiss the modal view controller.

- (void)messageComposeViewController:
(
MFMessageComposeViewController *)controller
didFinishWithResult:(MessageComposeResult)result
{

switch (result)
{
case MessageComposeResultCancelled:
NSLog(@"Cancelled");
break
;
case MessageComposeResultFailed:
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"MyApp" message:@"Unknown Error"
delegate:self cancelButtonTitle:@”OK”
otherButtonTitles: nil];
[alert show];
[alert release];
break;
case
MessageComposeResultSent:
break
;
default:
break;
}

[self dismissModalViewControllerAnimated:YES];
}
That’s it. Your app should now be able to send SMS using the new Message UI sheet. :-)

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

Friday, October 15, 2010

Rotating an image with bounds & unchanged ratio

- (void)scaleAndRotateImage:(UIImage *)image
{
int kMaxResolution = 320; // Or whatever

CGImageRef imgRef = image.CGImage;

CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);

CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
if (width > kMaxResolution || height > kMaxResolution) {
CGFloat ratio = width/height;
if (ratio > 1) {
bounds.size.width = kMaxResolution;
bounds.size.height = bounds.size.width / ratio;
}
else {
bounds.size.height = kMaxResolution;
bounds.size.width = bounds.size.height * ratio;
}
}

CGFloat scaleRatio = bounds.size.width / width;
CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
CGFloat boundHeight;
UIImageOrientation orient = image.imageOrientation;
switch(orient) {

case UIImageOrientationUp: //EXIF = 1
transform = CGAffineTransformIdentity;
break;

case UIImageOrientationUpMirrored: //EXIF = 2
transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
break;

case UIImageOrientationDown: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;

case UIImageOrientationDownMirrored: //EXIF = 4
transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
break;

case UIImageOrientationLeftMirrored: //EXIF = 5
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;

case UIImageOrientationLeft: //EXIF = 6
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;

case UIImageOrientationRightMirrored: //EXIF = 7
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeScale(-1.0, 1.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;

case UIImageOrientationRight: //EXIF = 8
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;

default:
[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];

}

UIGraphicsBeginImageContext(bounds.size);

CGContextRef context = UIGraphicsGetCurrentContext();

if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
CGContextScaleCTM(context, -scaleRatio, scaleRatio);
CGContextTranslateCTM(context, -height, 0);
}
else {
CGContextScaleCTM(context, scaleRatio, -scaleRatio);
CGContextTranslateCTM(context, 0, -height);
}

CGContextConcatCTM(context, transform);

CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[self setRotatedImage:imageCopy];
//return imageCopy;
}