iOS & Objective C Smarties Code Snippets by Marcio Valenzuela Santiapps.com
iOS & Objective C Smarties Code Snippets

Everyone loves Smarties!  And much the same way Smarties Candies make you smarter… today we are talking about Code Snippets that make you….er Smarter!  More than a source of cut/paste Objective C source code, this is meant to be a quick reference.  As such, some of these will be incomplete and I will be filling them up as I go along. 

1)   UIAlertView

UIAlertView *internetAlert = [[UIAlertView alloc] initWithTitle:@”No hay farmacias”

message:@”Favor cambie sus parámetros”

delegate:self

cancelButtonTitle:@”Cancelar”

otherButtonTitles:@”Ok”, nil];

[internetAlert show];

2)   NSNotification

//1. Register as observer of notifications in viewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveTestNotification:) name:@”TestNotification” object:nil];

//2. NSNotifCtr CLEANUP in viewDidUnload

[[NSNotificationCenter defaultCenter] removeObserver:self];

//4. Post notif to NSNotif in calling method OTHER CLASS

[[NSNotificationCenter defaultCenter]

postNotificationName:@”TestNotification”

object:self];

//3. Method to prove notif received…

– (void) receiveTestNotification:(NSNotification *) notification

{

if ([[notification name] isEqualToString:@”TestNotification”])

NSLog (@”Successfully received the test notification!”);

}

3)   UIActivityIndicator – NSTimer – then completion blocks

//1. Set activity indicator

UIApplication *sharedApplication = [UIApplication sharedApplication];

sharedApplication.networkActivityIndicatorVisible = YES;

//INSERT NSTimer here J

//2. Hide activity indicator

UIApplication *sharedApplication = [UIApplication sharedApplication];

sharedApplication.networkActivityIndicatorVisible = NO;

works the same with an IBOutlet UIActivityIndicator

4)   UISearchBar

UISearchBarDelegate, UISearchDisplayDelegate

@property (strong,nonatomic) NSMutableArray *filteredResultsArray;

@property (strong,nonatomic) IBOutlet UISearchBar *resultsSearchBar;

//UISearch in INIT or LOAD method

// Initialize the filteredResults array with its count of Locations NSManagedObjects

self.filteredResultsArray = [NSMutableArray arrayWithCapacity:[self.originalArray count]];

//ios6 refresh control ONLY

if ([UIRefreshControl class]) {

self.refreshControl = [[UIRefreshControl alloc] init];

[self.refreshControl addTarget:self action:@selector(reload) forControlEvents:UIControlEventValueChanged];

[self reload];

[self.refreshControl beginRefreshing];

} else {

//do nothing

}

//nORIS

if (tableView == self.searchDisplayController.searchResultsTableView) {

return [filteredResultsArray count];

} else {

return [self.originalArray count];

}

//cFRAIP

if (tableView == self.searchDisplayController.searchResultsTableView) {

// IF ITS A SEARCH TABLE…>>>>>>>>>>

//Use filteredResultsArray data

} else {

//Otherwise use self.originalArray

}

5)   Reminders & Events

/////////EVENTS

// SPECIAL CALENDAR OBJECT CLASS

#import <EventKit/EventKit.h>

+(EKEventStore*)eventStore;

+(EKCalendar*)calendar;

+(EKCalendar*)createAppCalendar;

// WHAT IT DOES

static EKEventStore* eStore = NULL;

+(EKEventStore*)eventStore{

//keep a static instance of eventStore

if (!eStore) {

eStore = [[EKEventStore alloc] init];

}

return eStore;

}

+(EKCalendar*)createAppCalendar

{

EKEventStore *store = [self eventStore];

//1 fetch the local event store source

EKSource* localSource = nil;

for (EKSource* src in store.sources) {

if (src.sourceType == EKSourceTypeCalDAV) {

localSource = src;

}

if (src.sourceType == EKSourceTypeLocal && localSource==nil) {

localSource = src;

}

}

if (!localSource) return nil;

//2 CREATE A NEW CALEDNAR FOR ITEMS!!!!!!!!!!!!!!!

EKCalendar* newCalendar = [EKCalendar calendarWithEventStore: store];

newCalendar.title = kAppCalendarTitle;

newCalendar.source = localSource;

newCalendar.CGColor = [[UIColor colorWithRed:0.8 green:0.2 blue:0.6 alpha:1] CGColor];

//3 save the calendar in the event store

NSError* error = nil;

[store saveCalendar: newCalendar commit:YES error:&error];

if (!error) {

return nil;

}

//4 store the calendar id

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

[prefs setValue:newCalendar.calendarIdentifier forKey:@”appCalendar”];

[prefs synchronize]; return newCalendar;

}

+(EKCalendar*)calendar{

//1

EKCalendar* result = nil;

EKEventStore *store = [self eventStore];

//2 check for a persisted calendar id

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

NSString *calendarId = [prefs stringForKey:@”appCalendar”];

//3

if (calendarId && (result = [store calendarWithIdentifier: calendarId])) {

return result;

}

//4 check if calendar name exists

for (EKCalendar* cal in store.calendars) {

if ([cal.title compare: kAppCalendarTitle]==NSOrderedSame) {

if (cal.immutable == NO) {

[prefs setValue:cal.calendarIdentifier

forKey:@”appCalendar”]; [prefs synchronize]; return cal;

}

}

}

//5 if no calendar is found whatsoever, create one

result = [self createAppCalendar];

//6

return result;

}

// ADD ENTRY FROM VC THRU CALEDNAR OBJECT

-(void)addItem:(NSDictionary*)item toCalendar:(EKCalendar*)calendar{

EKEvent* event = [EKEvent eventWithEventStore:[AppCalendar eventStore]];

event.calendar = calendar;

EKAlarm* myAlarm = [EKAlarm alarmWithRelativeOffset: – 06*60 ];

[event addAlarm: myAlarm];

NSDateFormatter* frm = [[NSDateFormatter alloc] init];

[frm setDateFormat:@”MM/dd/yyyy HH:mm zzz”];

[frm setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@”en_US”]];

event.startDate = [frm dateFromString:[show objectForKey:@”startDate”]];

event.endDate = [frm dateFromString:[show objectForKey:@”endDate”]];

event.title = [item objectForKey:@”title”];

event.URL = [NSURL URLWithString:[item objectForKey:@”url”]];

event.location = @”My Office”;

event.notes = [item objectForKey:@”tip”];

//add recurrence

NSNumber* weekDay = [item objectForKey:@”dayOfTheWeek”];

EKRecurrenceDayOfWeek* itemDay = [EKRecurrenceDayOfWeek dayOfWeek: [weekDay intValue]];

EKRecurrenceEnd* runFor3Months = [EKRecurrenceEnd recurrenceEndWithOccurrenceCount:12];

EKRecurrenceRule* myReccurrence = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:EKRecurrenceFrequencyWeekly interval:1

daysOfTheWeek:[NSArray arrayWithObject:itemDay] daysOfTheMonth:nil monthsOfTheYear:nil weeksOfTheYear:nil daysOfTheYear:nil setPositions:nil end:runFor3Months];

[event addRecurrenceRule: myReccurrence];

//1 save the event to the calendar

NSError* error = nil;

[[AppCalendar eventStore] saveEvent:event span:EKSpanFutureEvents commit:YES error:&error];

//2 show the edit event dialogue

EKEventEditViewController* editEvent = [[EKEventEditViewController alloc] init];

editEvent.eventStore = [AppCalendar eventStore]; editEvent.event = event;

editEvent.editViewDelegate = self;

[self presentViewController:editEvent animated:YES completion:^{

UINavigationItem* item = [editEvent.navigationBar.items objectAtIndex:0]; item.leftBarButtonItem = nil;

}];

}

//////REMINDERS

//EVENT CLASS OBJECT

– (id) init {

self = [super init];

if (self) {

_eventStore = [[EKEventStore alloc] init];

[_eventStore requestAccessToEntityType:EKEntityTypeEvent

completion:^(BOOL granted, NSError *error) {

if (granted) {

_eventAccess = YES;

} else {

NSLog(@”Event access not granted: %@”, error);

}

}];

[_eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) {

if (granted) { _reminderAccess = YES;

} else {

NSLog(@”Reminder access not granted: %@”, error);

}

}];

//Initialize the dispatch queue

_fetchQueue = dispatch_queue_create(“com.santiapps.fetchQueue”, DISPATCH_QUEUE_SERIAL);

}

return self;

}

//LOOP THRU CALENDARS

NSArray * allCalendars = [_eventStore calendarsForEntityType:EKEntityMaskEvent |

EKEntityMaskReminder];
NSMutableArray * writableCalendars = [NSMutableArray array]; for (EKCalendar * calendar in allCalendars) {

if (calendar.allowsContentModifications) { [writableCalendars addObject:calendar];

} }

EKCalendar *calendar = eventStore.defaultCalendarForNewEvents;

//CREATE EVENT

//1

EKEvent *event = [EKEvent eventWithEventStore:eventStore]; event.title = @”Hello world!”;
event.startDate = startDate;
event.endDate = endDate;

EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:-1800]; [event addAlarm:alarm];

event.calendar = eventStore.defaultCalendarForNewEvents;

//2

NSError *err;
BOOL saved = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];

if (!saved) {
NSLog(@”Error creating the event”);

}

//REMINDER

//1

EKReminder *reminder = [EKReminder reminderWithEventStore:eventStore];

reminder.title = @”Creating my first reminder”; reminder.calendar = [eventStore defaultCalendarForNewReminders];

NSCalendar *calendar =
[NSCalendar currentCalendar];

NSUInteger unitFlags = NSEraCalendarUnit |

NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;

NSDateComponents *dueDateComponents = [calendar components:unitFlags fromDate:dueDate];

//1.5. Set the due date

reminder.dueDateComponents = dueDateComponents;

//2

NSError *err;

BOOL success =

[eventStore saveReminder:reminder commit:YES error:&err];

if (!success) {
NSLog(@”Error creating reminder”);

}

6)   Local Notifications

//test notif

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:10];

UILocalNotification *localNotification = [[UILocalNotification alloc] init];

localNotification.fireDate = date;

localNotification.timeZone = [NSTimeZone defaultTimeZone];

localNotification.alertBody = @”I am a local notification!”;

localNotification.soundName = UILocalNotificationDefaultSoundName;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

7)   Sort NSArrays for tableviews

-(void)sort{

NSSortDescriptor *sortDescriptor;

sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@”distance” ascending:YES] autorelease];

NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

NSArray *sortedArray;

sortedArray = [self.annotationsToSort sortedArrayUsingDescriptors:sortDescriptors];

self.annotationsToSort = [(NSArray*)sortedArray mutableCopy];

[self.tableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.5];

}

8)   Contacts

// Read Contact list xml formatted (Array of Dictionaries)

//read directory here

dispatch_async(kBgQueue , ^{

contacts = [NSArray arrayWithContentsOfURL: kContactsList];

dispatch_async(dispatch_get_main_queue(), ^{

[self.tableView reloadData]; });

});

// Do this

//NO ADD THEM TO AB

dispatch_async(kBgQueue , ^{

NSString* request = [NSString stringWithFormat:@”%@?%@”, kContactsList, ids]; //1

NSData *responseData = [NSData dataWithContentsOfURL:[NSURL URLWithString:request]]; //2

//parse vCard data

ABAddressBookRef addressBook = ABAddressBookCreate(); //1

ABRecordRef record = ABPersonCreate(); //2

NSArray* importedPeople = (__bridge_transfer NSArray*)

ABPersonCreatePeopleInSourceWithVCardRepresentation( record, (__bridge CFDataRef)responseData); //3

CFBridgingRelease(record); //4

//define few constants

__block NSMutableString* message = [NSMutableString stringWithString:

@”Contacts imported AB. Add them in Facebook: “];

NSString* serviceKey = (NSString*)kABPersonSocialProfileServiceKey;

NSString* facebookValue = (NSString*)

kABPersonSocialProfileServiceFacebook;

NSString* usernameKey = (NSString*)kABPersonSocialProfileUsernameKey;

//loop over people and get their facebook

for (int i=0;i<[importedPeople count];i++) { //1

ABRecordRef personRef = (__bridge ABRecordRef) [importedPeople objectAtIndex:i];

ABAddressBookAddRecord(addressBook, personRef, nil);

//2

ABMultiValueRef profilesRef = ABRecordCopyValue( personRef, kABPersonSocialProfileProperty);

NSArray* profiles = (__bridge_transfer NSArray*) ABMultiValueCopyArrayOfAllValues(profilesRef);

//3

for (NSDictionary* profile in profiles) { //4

NSString* curServiceValue = [profile objectForKey:serviceKey]; //5

if ([facebookValue compare: curServiceValue] == NSOrderedSame) { //6

[message appendFormat: @”%@, “, [profile objectForKey: usernameKey]];

}

}

//7

CFBridgingRelease(profilesRef);

}

//save to addressbook

ABAddressBookSave(addressBook, nil);

CFBridgingRelease(addressBook);

//show done alert

dispatch_async(dispatch_get_main_queue(), ^{ [[[UIAlertView alloc]

initWithTitle: @”Done!” message: message

delegate: nil cancelButtonTitle:@”OK” otherButtonTitles:nil] show];

});

});

9)   Mapkit

//CHECK LOCATION SERVICES

-(void)checkLocationServices{

BOOL locationAllowed = [CLLocationManager locationServicesEnabled];

if (locationAllowed==NO) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Location Service Disabled”

message:@”Re-enable in Settings for this app.”

delegate:nil

cancelButtonTitle:@”OK”

otherButtonTitles:nil];

[alert show];

[alert release];

}

}

//GET LOCATION

-(void)getLocation{

locationManager = [[CLLocationManager alloc] init];

locationManager.delegate = self;

locationManager.distanceFilter = 10;

locationManager.desiredAccuracy = kCLLocationAccuracyBest;

[locationManager startUpdatingLocation];

//- (void)startMonitoringSignificantLocationChanges

_mapView.showsUserLocation = YES;

}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

self.userLocation = [locations lastObject];

NSLog(@”userLocation is %f, %f”, self.userLocation.coordinate.latitude, self.userLocation.coordinate.longitude);

CLLocationCoordinate2D zoomLocation;

zoomLocation.latitude = self.userLocation.coordinate.latitude;

zoomLocation.longitude = self.userLocation.coordinate.longitude;

NSLog(@”Using %g,%g”, zoomLocation.latitude, zoomLocation.longitude);

//StopUpdating Location so it wont change all the time

[locationManager stopUpdatingLocation];

}

//GET ANNOTATIONS

CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];

CLLocationDistance calculatedDistance = [pinLocation distanceFromLocation:self.userLocation];

annotation.distance = calculatedDistance/1000;

//PLOT ANNOTATIONS

-(void)plotAnnotations{

//Clean out old annotations

for (id<MKAnnotation> annotation in _mapView.annotations) {

[_mapView removeAnnotation:annotation];

}

//THIS LOGS THE LOCATIONSTOSORT ARRAY OF FVC

//NSLog(@”self.myLocationsToSort %@”, self.myLocationsToSort);

for (MyLocation *annotation in self.myLocationsToSort) {

//Add annotation to mapview

[_mapView addAnnotation:annotation];

}

}

– (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

static NSString *identifier = @”MyLocation”;

if ([annotation isKindOfClass:[MyLocation class]]) {

//test if mapviewnil

if (_mapView == nil) {

NSLog(@”NIL”);

}

MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [_mapView dequeueReusableAnnotationViewWithIdentifier:identifier];

if (annotationView == nil) {

annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];

annotationView.enabled = YES;

annotationView.canShowCallout = YES;

annotationView.image=[UIImage imageNamed:@”arrest.png”];

} else {

annotationView.annotation = annotation;

}

//instatiate a detail-disclosure button and set it to appear on right side of annotation

UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

//[infoButton addTarget:self action:@selector(showDetailView:annotationView.annotation) forControlEvents:UIControlEventTouchUpInside];

annotationView.rightCalloutAccessoryView = infoButton;

return annotationView;

}

return nil;

}

//GET ANNOTATIONS

//ZOOM INTO LOCATION

– (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {

// We have location, do your logic of setting the map region here.

CLLocationCoordinate2D zoomLocation;

NSLog(@”location in FirstVC %@”, self.userLocation);

//Test if userLocation has a value

NSLog(@”NOCITYSELECTED vDL FVC”);

zoomLocation.latitude = self.userLocation.coordinate.latitude;

zoomLocation.longitude = self.userLocation.coordinate.longitude;

CLLocationDistance visibleDistance = 5000; // 5 kilometers

MKCoordinateRegion adjustedRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, visibleDistance, visibleDistance);

[_mapView setRegion:adjustedRegion animated:YES];

}

//TAP ON PINS – ANNOTATIONS

//Called when disclosure tapped

– (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{

if (![view.annotation isKindOfClass:[MyLocation class]])

return;

// use the annotation view as the sender

[self performSegueWithIdentifier:@”DetailVC” sender:view];

}

10)                  UICustomization/Appearance

[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];

[self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@”Futura” size:10.0f], UITextAttributeFont, nil] forState:UIControlStateNormal];

UIImage *gradientImage32 = [[UIImage imageNamed:@”FirstCellLogo.png”] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

[[UINavigationBar appearance] setBackgroundImage:gradientImage32 forBarMetrics:UIBarMetricsDefault];

[self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@”Futura” size:10.0f], UITextAttributeFont, nil] forState:UIControlStateNormal];

[[UITabBar appearance] setSelectedImageTintColor:[UIColor redColor]];

11)                  LetterPress Effect

//letterpress effect the label

//NSMutableAttributedString

NSMutableAttributedString *restName = [[NSMutableAttributedString alloc] initWithString:self.attributionText.text];

[restName addAttributes:@{ NSTextEffectAttributeName : NSTextEffectLetterpressStyle, NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline] } range:NSMakeRange(0, restName.length)];

self.attributionText.attributedText = restName;

12)                  UIGesture

13)                  iCloud

14)                  Library.a

15)                  Instruments

16)                  Checklist App

17)                  UICollectionView & UIContainerView & SplitVC & Popover

18)                  SlideUp

19)                  Raised Tabbar

20)                  Passbook

21)                  AR

22)                  Export Data

23)                  TF

24)                  iAds & AppiRater

25)                  TimeCmoparator – String Parsing

26)                  UIApplicationDelegate sharedApplication & its methods

27)                  NSUserDefaults

// call the store object

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// set an object for it

[prefs setObject:imageView.image forKey:@”keyToLookupImage”];

// call sync to save it

[prefs synchronize];

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

UIImage *retrievedImage = [prefs stringForKey:@”keyToLookupImage”];

imageView.image = retrievedImage;

28)                  Façade design pattern

29)                  Protocols & Delegates

30)                  InAppPurchases

31)                  Datepicker/uipicker

32)                  NSOperation

33)                  Date Formatter

NSDate *date = [NSDate date];

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

[dateFormatter setDateStyle:NSDateFormatterShortStyle];

[dateFormatter setTimeStyle:NSDateFormatterFullStyle];

NSString *formattedDateString = [dateFormatter stringFromDate:date];

NSLog(@”formattedDateString for locale %@: %@”,

[[dateFormatter locale] localeIdentifier], formattedDateString);

timeLabel.text = [dateFormatter stringFromDate:date];

34)                  Letterpress Effect

35)                  asd

Leave a Reply