Skip to main content

Great UIKit/Objective-C code snippets



New to Objective-C iPhone/iPod touch/iPad development, but I'm starting to discover lots of power in one-liners of code such as this:







[UIApplication sharedApplication].applicationIconBadgeNumber = 10;







Which will display that distinctive red notification badge on your app iphone with the number 10.





Please share you favorite one or two-liners in Objective-C for the iPhone/iPod touch/iPad here. PUBLIC APIs ONLY .


Comments

  1. Open an URL in Safari

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com/"]];


    Hide the status bar

    [[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];


    Dial a Phone Number (iPhone Only)

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


    Launch the Apple Mail

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://mymail@myserver.com"]];


    stop responding to touch events

    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];


    active the touch events

    [[UIApplication sharedApplication] endIgnoringInteractionEvents];


    Show the network Activity Indicator

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;


    Hide the network Activity Indicator

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;


    Prevents iPhone goes into sleep mode

    [UIApplication sharedApplication].idleTimerDisabled = YES;

    ReplyDelete
  2. Display an alert window:

    UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"too many alerts" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
    [alert show]

    Get the path to the Documents folder:

    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];

    Push another view controller onto the Navigation Bar:

    [self.navigationController pushViewController:anotherVC animated:YES];

    Fade away a UIView by animating the alpha down to 0:

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1]; // fade away over 1 seconds
    [aView setAlpha:0];
    [UIView commitAnimations];

    Get the name of the app

    self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];

    Change the status bar to black

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];

    Change the style of the navigation bar (from in a view controller):

    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;

    Save a NSString into NSUserDefaults:

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:loginName forKey:kUserLoginName];

    Get an NSString from NSUserDefaults:

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];


    NSString* loginName = [defaults stringForKey:kUserLoginName];
    Check to make sure an objects support a method before calling it:

    if ([item respondsToSelector:@selector(activateBOP:)]) {
    [item activateBOP:closeBOP];
    }

    Log the name of the class and function:

    NSLog(@"%s", __PRETTY_FUNCTION__);

    Add rounded corners and/or a border around any UIView item (self)

    self.layer.borderColor = [UIColor whiteColor].
    self.layer.cornerRadius = 8; // rounded corners
    self.layer.masksToBounds = YES; // prevent drawing outside border

    Open Google Maps app with directions between two lat/long points

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f&dirflg=d", start.latitude, start.longitude, finish.latitude, finish.longitude];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];

    ReplyDelete
  3. Save bool to User Defaults

    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Yes Bool"];


    Copy a file from x to y

    [[NSFileManager defaultManager] copyItemAtPath:x toPath:y error:nil];


    Display a new view

    [self presentModalViewController:(UIViewController *) animated:YES];


    Screen touches method

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


    Get documents directory

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];


    Load URL

    [MyWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://couleeapps.hostei.com"]]];


    Get Current Date and time:

    NSCalendar *gregorian = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];


    Own enum type:

    typedef enum {
    a = 0, b = 1, c = 2
    } enumName;


    Quartz draw arc

    CGContextRef ctxt = UIGraphicsGetCurrentContext();
    CGContextAddArc(ctxt, x, y, radius, startDeg, endDeg);

    ReplyDelete
  4. Make the device vibrate:

    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);


    Open the Messages app with a specific phone number:

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


    Stop responding to touch events:

    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];


    Start responding again:

    [[UIApplication sharedApplication] endIgnoringInteractionEvents];


    And finally, the single line of code browser:

    [[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: [urlText stringValue]]]];

    ReplyDelete
  5. Change the title on the back button on a UINavigationView. Use this code on the UINavigationController before pushing the view

    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style: UIBarButtonItemStyleBordered target:nil action:nil];


    self.navigationItem.backBarButtonItem = backBarButtonItem;
    [backBarButtonItem release];

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?