Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Last active December 14, 2015 02:19
Show Gist options
  • Select an option

  • Save lamprosg/5012748 to your computer and use it in GitHub Desktop.

Select an option

Save lamprosg/5012748 to your computer and use it in GitHub Desktop.
(iOS) Useful small actions and codes
//Check if a value exists in an NSMutableArray
if ([mutableArray indexOfObject:@"value"] == NSNotFound)
//Add rounded corners
CALayer * shareViewLayer = shareBlogView.layer;
[shareViewLayer setMasksToBounds:YES];
[shareViewLayer setCornerRadius:5.0];
//Add shadow to a view
someView.layer.shadowOpacity = 0.75f;
someView.layer.shadowRadius = 5.0f;
someView.layer.shadowColor = [UIColor blackColor].CGColor;
if ([StoreDataUtils isSeeingListForFirstTime])
{
//Show List info
infoView = [[UIView alloc] initWithFrame:CGRectMake(0, self.navigationController.view.bounds.origin.y,
CGRectGetMaxX(self.tableView.bounds), 0)];
infoView.backgroundColor = [UIColor grayColor];
infoView.layer.opacity = 0.8;
UIButton *dismissButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
dismissButton.titleLabel.font = [UIFont systemFontOfSize:13];
[dismissButton setTitle:L(dismiss) forState:UIControlStateNormal];
[dismissButton addTarget:self action:@selector(dismissListInfo) forControlEvents:UIControlEventTouchUpInside];
[dismissButton sizeToFit];
dismissButton.frame = CGRectMake(CGRectGetMaxX(self.tableView.bounds) - CGRectGetWidth(dismissButton.frame)-kLeftRightPadding,
0,
CGRectGetWidth(dismissButton.frame), CGRectGetHeight(dismissButton.frame));
[infoView addSubview:dismissButton];
UILabel *listInfoLabel;
listInfoLabel = [[UILabel alloc] initWithFrame:CGRectMake(kLeftRightPadding, self.navigationController.view.bounds.origin.y+35,
CGRectGetMaxX(self.tableView.bounds)-CGRectGetWidth(dismissButton.frame)-20,0)];
listInfoLabel.backgroundColor = [UIColor clearColor];
listInfoLabel.numberOfLines = 0;
listInfoLabel.lineBreakMode = NSLineBreakByWordWrapping;
listInfoLabel.textColor = [UIColor whiteColor];
listInfoLabel.font = [UIFont systemFontOfSize:13];
listInfoLabel.text = L(listInfoLabel);
[infoView addSubview:listInfoLabel];
[self.navigationController.view addSubview:infoView];
[UIView animateWithDuration:0.5 animations:^{
CGRect frame1 = infoView.frame;
frame1.size.height = 80;
infoView.frame = frame1;
CGRect frame2 = dismissButton.frame;
frame2.origin.y = self.navigationController.view.bounds.origin.y+26;
dismissButton.frame = frame2;
CGRect frame3 = listInfoLabel.frame;
frame3.size.height = 30;
listInfoLabel.frame = frame3;
}];
[infoView release];
[listInfoLabel release];
[dismissButton release];
}
-(NSURL*) getURLFromTweet:(NSString*)tweet {
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:tweet options:0 range:NSMakeRange(0, [tweet length])];
NSURL *url;
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypeLink) {
url = [match URL];
NSLog(@"found URL: %@", url);
//Make the URLs blue
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:tweet];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:[match range]];
self.tweet.attributedText = str;
}
}
return url;
}
+(void) loadAsyncImage: (UIImageView *)imageView fromURL:(NSString *)url {
//Get hashed representation for image url
NSString *hashed = [Util MD5Hash:url];
//Construct image path
NSString *imagePath = [NSString stringWithFormat:@"%@/%@", NSTemporaryDirectory(), hashed];
//Checks if image exists
BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
if (imageExists) {
NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:imageData];
imageView.image = image;
} else {//Load image from url
/************/
//Lazy loading images (Asychronous call)
imageView.image = [UIImage imageNamed:@""];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.frame = CGRectMake(imageView.frame.size.width/2-spinner.frame.size.width/2,
imageView.frame.size.height/2-spinner.frame.size.height/2,
spinner.frame.size.width, spinner.frame.size.height);
[imageView addSubview:spinner];
[spinner startAnimating];
NSURL *urlObject = [NSURL URLWithString:url];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlObject];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
NSURLResponse *response = nil;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
UIImage *image = [[UIImage alloc] initWithData:receivedData];
dispatch_async(dispatch_get_main_queue(), ^{
[spinner stopAnimating];
[spinner removeFromSuperview];
imageView.image = image;
//Store image to tmp for later use
[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
});
});
/************/
}
}
//Util class MD5Hash function
+ (NSString *)MD5Hash: (NSString *)input {
const char *cStr = [input UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
if (cStr == nil)
return @"";
CC_MD5( cStr, strlen(cStr), result );
return [NSString stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ];
}
//Make a custom button
//Or make one in the navigation bar
UIBarButtonItem *timefilterbtn;
timefilterbtn = [[UIBarButtonItem alloc] initWithTitle:@"T" style:UIBarButtonItemStylePlain target:self action:@selector(showTimeFilter)];
//TimeFilterViewController is the view we will show inside the popup (ex. table view controller)
TimeFilterViewController *timefilterviewcontroller;
UIPopoverController *timefilterpopover;
..
//Initialize popovers
timefilterviewcontroller = [[TimeFilterViewController alloc] init];
timefilterviewcontroller.delegate=self; //Yes there will be a protocol there
timefilterpopover = [[UIPopoverController alloc] initWithContentViewController:timefilterviewcontroller];
//Make a protocol and delegate variable in the TimefilterViewController and set the delegate to your main view controller
-(void) showPopOver
{
if ([timefilterpopover isPopoverVisible])
{
[timefilterpopover dismissPopoverAnimated:YES];
}
else
{
//the rectangle here is the frame of the object that presents the popover in case the popup isn't in the nav bar
// CGRect popRect = CGRectMake(self.btnShowPopover.frame.origin.x,
// self.btnShowPopover.frame.origin.y,
// self.btnShowPopover.frame.size.width,
// self.btnShowPopover.frame.size.height);
[timefilterpopover setPopoverContentSize:CGSizeMake(POPOVERWIDTH,POPOVERHEIGHT)];
//Custom
//[timefilterpopover presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
//In the nav bar
[timefilterpopover presentPopoverFromBarButtonItem:timefilterbtn permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
}
//In iPad !
MyModalViewController *targetController = [[[MyModalViewController alloc] init] autorelease];
targetController.modalPresentationStyle = UIModalPresentationFormSheet;
targetController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; //transition shouldn't matter
[self presentModalViewController:targetController animated:YES];
targetController.view.superview.frame = CGRectMake(0, 0, 200, 200);//it's important to do this after
presentModalViewController targetController.view.superview.center = self.view.center;
//ASCII codes to NSString
//62 is the interger value of ">"
[string stringByAppendingString:[NSString stringWithFormat:@" %c", 62]];
//Get thumbnail image from a video
NSString *str = [[self.vedioArray objectAtIndex:i] valueForKey:@"vName"];
NSURL *videoURL = [NSURL URLWithString:str] ;
MPMoviePlayerController *player = [[[MPMoviePlayerController alloc] initWithContentURL:videoURL]autorelease];
UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
player = nil;
//Get navigation controller, tabbar controller etc from the appdelegate
//Get nav. controller
((AppDelegate*)[UIApplication sharedApplication].delegate).mainNavCtrl
//Get view controller
[((AppDelegate*)[UIApplication sharedApplication].delegate).mainNavCtrl getViewControllerForTab:0]
//run a function
[[((AppDelegate*)[UIApplication sharedApplication].delegate).mainNavCtrl getViewControllerForTab:0] performSelector:@selector(setNeedUpdate)];
//Check Device Orientation
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if(orientation == 0) //Default orientation
//UI is in Default (Portrait) -- this is really a just a failsafe.
else if(orientation == UIInterfaceOrientationPortrait)
//Do something if the orientation is in Portrait
else if(orientation == UIInterfaceOrientationLandscapeLeft)
// Do something if Left
else if(orientation == UIInterfaceOrientationLandscapeRight)
//Do something if right
//Checking iOS version
[[[UIDevice currentDevice] systemVersion] floatValue] //returns 6.0, 5.0 or whatever the version is
//Load a storyboard view with its viewcontroller
UIStoryboard *storybrd = [UIStoryboard storyboardWithName:@"YOURSTORYBOARDNAME" bundle:nil];
MyViewController *vc =[storybrd instantiateViewControllerWithIdentifier:@"STORYBOARDID"];
[self.navigationController pushViewController:vc animated:YES];
//Switch Views with Animation
//check if the view is loaded (being in the superview)
if (self.yellowViewController.view.superview == nil) //if not
{
//If yellowView hasn't been loaded yet, load it
if (self.yellowViewController == nil)
{
self.yellowViewController = [[BIDYellowViewController alloc] initWithNibName:@"YellowView" bundle:nil];
}
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
//Remove bluw view
[self.blueViewController.view removeFromSuperview];
//Show yellowView
[self.view insertSubview:self.yellowViewController.view atIndex:0];
}
- (IBAction)textFieldDoneEditing:(id)sender
{
[sender resignFirstResponder];
}
- (IBAction)backgroundTap:(id)sender
{
[self.nameField resignFirstResponder];
[self.numberField resignFirstResponder];
}
- (IBAction)sliderChanged:(UISlider *)sender
{
int progress = lroundf(sender.value);
self.sliderLabel.text = [NSString stringWithFormat:@"%d", progress];
}
- (IBAction)switchChanges:(UISwitch *)sender
{
BOOL setting = sender.isOn;
[self.leftSwitch setOn:setting animated:YES];
[self.rightSwitch setOn:setting animated:YES];
}
- (IBAction)toggleControls:(UISegmentedControl *)sender
{
// 0 == switches index
if (sender.selectedSegmentIndex == 0)
{
self.leftSwitch.hidden = NO;
self.rightSwitch.hidden = NO;
self.doSomethingButton.hidden = YES;
}
else
{
self.leftSwitch.hidden = YES;
self.rightSwitch.hidden = YES;
self.doSomethingButton.hidden = NO;
}
}
//OPEN A URL IN SAFARI
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com/"]];
//DIAL A NUMBER
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://9662256888"]];
//LAUNCH MAIL AND SEND AN EMAIL
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://mymail@myserver.com"]];
//PREVENT SLEEP MODE
[UIApplication sharedApplication].idleTimerDisabled = YES;
//STOP RESPONDING TO TOUCHES
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
//RESUME RESPONDING TO TOUCHES
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
//DISPLAY THE NAME OF YOUR APPLICATION
self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
//CHANGE THE STYLE OF A NAVIGATION BAR
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
//GET THE CURRENT DATE AND TIME
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
//MAKE A VIBRATION
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
//DISPLAY THE NUMBER OF LAUNCHES
NSUserDefaults *countDefaults;
int launchCount;
countDefaults = [NSUserDefaults standardUserDefaults];
launchCount = [countDefaults integerForKey:@"launchCount" ] + 1;
[countDefaults setInteger:launchCount forKey:@"launchCount"];
[countDefaults synchronize];
NSLog(@"Launch number: %i", launchCount);
//CONFIGURING A UISCROLLVIEW
[scrollView setScrollEnabled:YES];
[scrollView setContentSize:CGSizeMake(320, 1400)];
//SET TITLE OF A VIEW IN A UIVIEWCONTROLLER
viewController.title = @"Title Here...";
//SET THE FONT AND SIZE OF A UITEXTVIEW
[thankYouTextView setFont:[UIFont fontWithName:@"Helvetica" size:16]];
//SET THE FONT SIZE OF A UILABEL
[textView setFont:[UIFont fontWithName:@"Helvetica" size:16]];
//PRESENTING A UIVIEWCONTROLLER
ViewController *viewController = [[ViewController alloc] init];
viewController = @"Title Here...";
[self.navigationController viewController animated:YES];
//HIDING THE BACK BUTTON IN A NAVIGATION CONTROLLER
self.navigationItem.hidesBackButton = YES;
//SET BACKGROUND OF VIEW
self.view.backgroundColor = [UIColor colorWithHue:1.0 saturation:0.0 brightness:0.6 alpha:1.0];
//GIVE APP ICON A BADGE NUMBER
[UIApplication sharedApplication].applicationIconBadgeNumber = 10;
//ALIGN UILABEL TEXT
titleLabel.textAlignment = UITextAlignmentCenter;
//SET BACKGROUND OF TAB BAR
UIImage *tabBarBackground = [UIImage imageNamed:@"TabBarOverlay.png"];
[rootController.tabBar setBackgroundImage:tabBarBackground];
//Create and add logo to a view
UIView *preTableView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetMaxX(self.tableView.bounds), 80 + kTopPadding * 2)];
UIImage *logo = [UIImage imageNamed:@"logo_home.png"];
UIImageView *imageHolder = [[UIImageView alloc] initWithFrame:CGRectMake(self.tableView.bounds.size.width / 2 - 83 / 2, kTopPadding, 83, 80)];
imageHolder.image = logo;
[preTableView addSubview:imageHolder];
//OR
UIImage *image = [UIImage imageNamed:@"search_results_empty.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView sizeToFit];
//Create info button
UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
CGRect frame = CGRectMake(CGRectGetMaxX(self.tableView.bounds) - infoButton.frame.size.width - kLeftRightPadding, kTopPadding, infoButton.frame.size.width, infoButton.frame.size.height);
infoButton.frame = frame;
[infoButton addTarget:self action:@selector(infoBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[preTableView addSubview:infoButton];
//Another Button
sendButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
[sendButton setTitle:L(remindMe) forState:UIControlStateNormal];
[sendButton addTarget:self action:@selector(remindPassword) forControlEvents:UIControlEventTouchUpInside];
[sendButton sizeToFit];
sendButton.frame = CGRectMake(self.view.bounds.size.width/2 - sendButton.frame.size.width/2, 25,
CGRectGetWidth(sendButton.frame), CGRectGetHeight(sendButton.frame));
//Get string's width
NSString *lbl = L(addPhoto);
CGFloat labelwidth = [lbl sizeWithFont:kAddPhotoBtnFont].width;
//Strech a specific part of a button
UIImage *button = [[UIImage imageNamed:@"addPhoto.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0, 20.0, 30.0, 20.0)];
//Add an action to a label
footerLbl = [[UILabel alloc] init];
footerLbl.backgroundColor = [UIColor clearColor];
footerLbl.numberOfLines = 0;
footerLbl.lineBreakMode = UILineBreakModeWordWrap;
footerLbl.textColor = [UIColor whiteColor];
footerLbl.text = L(promptForSignUp);
footerLbl.font = [UIFont systemFontOfSize:12];
CGSize maxSize = CGSizeMake(CGRectGetWidth(self.view.bounds)-2*padding, MAXFLOAT);
CGSize requiredSize = [footerLbl sizeThatFits:maxSize];
footerLbl.frame = CGRectMake(floor((CGRectGetWidth(self.view.bounds)-requiredSize.width)/2), padding, requiredSize.width, requiredSize.height);
footerLbl.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleBetweenLoginAndSignUp)];
[footerLbl addGestureRecognizer:tapGr];
[tapGr release];
//Creat textfield programmatically
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 40)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = @"enter text";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.delegate = self;
[self.view addSubview:textField];
[textField release];
//Textfield delegate
//When the user hits the enter key on the keyboard, this method will be called
#pragma mark - UITextFieldDelegate methods
- (BOOL) textFieldShouldReturn:(UITextField *)textField {
//Your code here...
[textField resignFirstResponder];
return YES;
}
//Create scrollview
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kTopPadding * 5, CGRectGetMaxX(self.tableView.bounds), 80)];
scrollView.clipsToBounds = NO;
scrollView.scrollEnabled = YES;
[scrollView setShowsHorizontalScrollIndicator:NO];
[scrollView setShowsVerticalScrollIndicator:NO];
//Adding background image to a viewcontroller
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_cork.png"]];
//Prost table footer
UIView *footer = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds),
CGRectGetMaxX(self.view.bounds) - sendButton.frame.origin.y)] autorelease];
//Present and Dismiss modal view controller
//Present
[self presentViewController:pNewController animated:YES completion:nil];
//Dismiss
[self dismissViewControllerAnimated:controller completion:nil];
/*******************************************************/
//Compress image in JPG
UIImage *image = [UIImage imageNamed:@"anyImage.png"];
NSData *data = UIImageJPEGRepresentation(image, 0.5);
// 0.5 is float value it is 1.0 for same resolution
UIImage *newImage = [UIImage imageWithData:data];
/*******************************************************/
/*******************************************************/
//Play audio
//Add AVFoundation.framework to the project
AVAudioPlayer *audioPlayer;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
//There are also
audioPlayer.volume = 0.5; // 0.0 - no volume; 1.0 full volume
audioPlayer.currentTime = 10; // jump to the 10 second mark
[audioPlayer pause];
[audioPlayer stop]; // Does not reset currentTime; sending play resumes
/*******************************************************/
// get only the date/time part of a NSDate object
- (NSDate*) datePartFromDate:(NSDate*)date {
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
return [[NSCalendar currentCalendar] dateFromComponents:comps];
}
//Inspect the reference count manually
CFIndex rc = CFGetRetainCount((__bridge CFTypeRef)myObj);
//There is also CFGetAllocator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment