Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Friday, December 20, 2013

iOS Get App Window

So, you want to get the iOS app window, huh?

Terminology is one of the great barriers to moving from language-to-language and platform-to-platform, so its no surprise that some people are going to want to search for different terms, so we cover a few cases in this post, just to make sure we're getting the answer you're actually after:

Case #1, you're really wanting to get the current UIViewController displayed in your application:

A. When you're using a NavigationController

  // Way #1: Get the topmost ViewController (current) in this navigation hierarchy.
  UIViewController *currentViewController = [[self.navigationController viewControllers] lastObject];

  // Way #2: Ask your UINavigationController which ViewController is the visible one.
  UIViewController *currentViewController = self.navigationController.visibleViewController;

B. When you're not (presumably nested modal views or other)

- (UIViewController *) getTopViewController
{
  UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;

  UIViewController *viewController = keyWindow.rootViewController;
  while(viewController.presentedViewController){
    viewController = viewController.presentedViewController;
  }
  
  return viewController;
}

Case #2: You actually want the key window:

  UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;

... which is a window that "manages and coordinates the views an app displays on the device screen", and of which your app probably only has one.

Case #3: What you really want is the UIView of the current UIViewController so you can manipulate it somehow, in which case you want to do:

  // I am in a UIViewController, so I can get my view like this
  UIView *view = [self view];

Well, hopefully that covers it, but if not, please leave a comment on a case we might have missed. Thanks, and please give us a +1 if you have the inclination!


Read More

Thursday, December 19, 2013

iOS Get First Day of Year

So, you want an NSDate representing the start of this year, huh?

Well, what's the fun in just getting the start of the current year. Here's a bit of code that will give you the start of the current year as well as the start of any year before or after it:

Here's how you can get the start of this year:


  // Lets get the start of this year, but we could do next year (1) or last year (-1)
  int yearOffset = 0;
  
  // Date representing right now
  NSDate *date = [[NSDate alloc] init];
  
  NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  NSDateComponents * calComponents = [cal components: NSYearCalendarUnit fromDate:date];

  [calComponents setYear:([calComponents year] + yearOffset)];
  

  NSDate *startOfYearWithOffset = [cal dateFromComponents:calComponents];
 

In the above code, its the yearOffset that gives you the ability to get the start of next year (yearOffset = 1) or last year (yearOffset = -1). Hope that helps you.

If you love us with undying passion for what we just taught you, then please give us a +1 and tell your next door neighbors about us... you've been needing a good excuse to introduce yourself anyway.


Read More

iOS Last Day of Week

So, you'd like to get an NSDate representing the last day of the current week, huh?

Well, firstly, lets define what we mean by last day of the week. Of course, we mean Saturday, why wouldn't we, right? Well, there tends to be a lot of discussion around this, and we don't want to meddle with ongoing debates on the merits of treating Sunday as the last day of the week. For our purposes, Sunday is the first day of the week, and Saturday is the last day of the week.

Here's a quick example of how to get the (beginning of) the last day of the week:

  NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

  NSDate *date = [[NSDate alloc] init];
  
  NSDateComponents *calComponents = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:date];

  // this will give you current day of week
  int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date] weekday];
  
  // Offset to Saturday
  int dayOfWeekOffset = 6;
  
  // this will give you Saturday (the last day of the week)
  [calComponents setDay:([calComponents day] - ((dayofweek) - 1) + dayOfWeekOffset)];

  NSDate *lastDayOfWeek = [cal dateFromComponents:calComponents];

That seems like a lot of code, but all you are doing is breaking down dates into their components and adding and/or subtracting components. Its easy to get it mixed up in your head the first go-round. Best of luck!

If you're viewing this page as a castaway from a deserted island somewhere in the Pacific and you need help, reach out to us, otherwise, if you found this post useful, please give us a +1, thanks!


Read More

iOS NSDate Get Start of Day

So, you want an NSDate representing the start of today, huh?

Sometimes, we like to give you a bit more capability than you ask for, just so you can reuse our code in more circumstances. Here's a bit of code that will give you the start of the current day as well as the start of any day before or after it:

Here's how you can get the start of today:

  int dayOffset = 0;
  
  NSDate *rightNow = [[NSDate alloc] init];
  
  NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  NSDateComponents * calComponents = [cal components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:rightNow];
  
  // Current day of week, with hours, minutes and seconds zeroed-out
  int today = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:rightNow] weekday];
  
  [calComponents setDay:([calComponents day] + dayOffset)];

  NSDate *beginningOfDay = [cal dateFromComponents:calComponents];

In the above code, its the dayOffset integer that gives you the ability to get the start of tomorrow (dayOffset = 1) or yesterday (dayOffset = -1). That should give you plenty of power.

If you found this so helpful that you just want to throw money at us, why not throw it instead at your local charity? And if you don't have any money to throw around, we'll sure take a +1 instead. Thanks!



Read More

iOS Get Selected Rows in a UITableView

So, you want to know what rows are currently selected in a UITableView, huh?

If you're using a tableview to allows single-selection but you do not segue to another controller with the selected record, you may find the need to know what rows are currently selected. If that is your aim, then have no fear, I have some code for you here:


  NSIndexPath *selectedRowPath = [self.tableView indexPathForSelectedRow];


Now, if your tableview's datasource is an array that is a property of your current ViewController, then all is well, and you can get the Object that is actually representative of the selection in the table like so:


  int rowIndex = selectedRowPath.row;  
  NSObject *selectedObject = [self.datasourceArray objectAtIndex:rowIndex];


Hopefully that sets you back on the road to creating value. Speaking of, if you have a mind to give us a +1, please do so, as it creates a lot of value for us. Thank you!




Read More

iOS Get Class Name for Object

So, you have an object for which you would like to know the class name, right?

NSObjects all come with a class accessor method which you can call to determine the type of class your object is, whether you made the object yourself (extending NSObject or some inheritor from NSObject), or whether you're using an out-of-the-box object like NSString, they all respond to the "class" method.

Here's an example:


  NSString *myObject = @"Just a test!";
  
  Class theClass = [myObject class];


But, alas, we're not quite done, because you wanted to get the NAME the class... I didn't forget, see? If you have a Class object now, you can get the class name like so:



  NSString *className = NSStringFromClass(theClass);



Hopefully that gets you where you need to be, see you next time! 

Oh, and if you're still here, we'd love it if you gave us a +1 out of the kindness of your heart.


Read More

Wednesday, December 18, 2013

iOS Get Badge Number

So, you want to get the number currently set on the iOS notification badge, do you?

One of the coolest and underused features of iOS (as it pertains to small, independent developers) is the notification badge. Setting the badge number tells the user that there is something important to do, and when they open the application, they should expect to see something interesting and valuable. But, since you're coding this, you may not care about conventions, you may just say "Just show me the code, dangit!". You sir, are a gentleman with no time for dickering about.

Here is how you get the current value of the notification badge on the iOS home screen:


  NSInteger *badgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber;

I tip my hat to you dear sir/maam, and wish you a pleasant day.

If you're just arriving from another planet and have never seen the internet before, you should know that you happened upon the BEST WEBSITE IN THE WORLD (just kidding)! Now, if you'll kindly give us a +1, you'll never lose us as you travel the information superhighway. Godspeed your return traveler!


Read More

iOS Get Bounds of Screen

So, you want to know how big the screen is (bounds) on an iOS device, eh?

Unfortunately, you can't rely on the screen sizes that you know right now, as device releases tend to confound the most thorough static-coders who rely on fixed sized. Sigh, those were the days. Now, you don't have it nearly as bad as the Android folks have it, not by a long shot, so the variance of screen sizes is more of an annoyance than anything. So, since you're the kind of person who likes to dynamically calculate screen size, then I have some code for you.

Here's an example of how to get the iOS screen bounds:


  CGRect screenBoundsRect = [[UIScreen mainScreen] bounds];
  
  // Now get the width/height of the screen
  CGFloat width = screenBoundsRect.size.width;
  CGFloat height = screenBoundsRect.size.height;


You should now thank your lucky stars that you chose iOS, if only for the limited number of devices of various sizes and memory constraints. Heaven help us that we ever see days like Android has seen.

If you liked this post because you just climbed down from the mountains, have a manly beard (or are otherwise roughly-shod and wear flannel), and you appreciate the taste of cold-brewed iOS code examples, then give us a +1 and we'll show you the world. Now, go chop some trees.


Read More

iOS Create a Class Instance by Name

So, you want to create an object instance from a Class object or NSString, eh?

Reflection, as it is more commonly known in Java parlance, is a super-power that allows you to go from a String name to an actual living, breathing, object instance.

If you saw our previous example, we showed you how to get a Class instance from a String name. Now, we'll take that example a little further and show you how to create an instance from it. Here we go:


  // Get a Class object from a NSString... magic!
  Class dictionaryClass = NSClassFromString(@"NSMutableDictionary");
  
  // Use 'reflection' to create an NSDictionary
  NSMutableDictionary *dict = [[dictionaryClass alloc] init];
  
  [dict setObject:@"Test" forKey:@"TestKey"];
  
  // Yep, its
  NSLog(@"%@", [dict objectForKey:@"TestKey"]);
  
  // >> Test

99.999-proof magic right there.

If you found this helpful, please give us a +1 and we'll stay at the top of your searches when you need help again!


Read More

iOS Core Data NSFetchRequest Fetch All Entities Example

So, you want a example of performing an NSFetchRequest in CoreData to fetch all of one kind of Entity, huh?

Lets say you have an entity called Events, which is a schedule of upcoming things you want to list in a table view... now, the whole UITableView thing, we won't go into that now (we'll link to that discussion below), but lets just suppose that it suffices that we want to fetch the list of events, heck, all of the event entity objects we have on hand. How would we do that?

Here's an example I cooked up, which fetches all event entities from the database and spits out an error on the console if anything goes wrong:

+(NSArray *)getAllEventsInManagedObjectContext:(NSManagedObjectContext *)context
{    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"1==1"];
    [request setPredicate:predicate];
    
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
    
    request.sortDescriptors = [NSArray arrayWithObject:descriptor];
    
    NSError *error = nil;
    NSArray *events = [context executeFetchRequest:request error:&error];
  
    if(error){
      NSLog(@"%@", error);
    }
  
    return events;
}

"That's all well and good, you say, but I need an example that shows how to use predicates".. if this is the case, checkout our post on "iOS NSFetchRequest with Predicates Example".

If you'd like to hear more about displaying entities in a UITableView, checkout our article on "How to Show Entities in a UITableView in iOS".

If you found this article helpful, why not give us a +1. And if you do, thank you very much!


Read More

iOS Get Battery Level

So, you want to programatically find your battery level on your iOS device?

The battery indicator on your iOS device is a useful indicator of how much battery you have remaining, and while it can't tell you how much time you have left, determining that a battery is withing 20% of shutting down is a useful thing to know, especially if you want to switch your app to operating in a less-CPU-intensive way. In my case, I record audio, and politely inform the user that their battery limit is approaching interesting levels.

If you want to determine the current battery level on your iOS device, here's an example of how to do it:


  float batteryLevel = [UIDevice currentDevice].batteryLevel;

Best practices suggest switching to a less CPU intensive mode when you run up against battery limits, though few people implement such things, its always a good idea to at least warn the user to save progress at these times, especially if the app is a mission-critical component to their work.

If you like to drink soda, juice, or water... we do too! We have so much in common. You should give us a +1 so you don't lose us... and we'll see you again soon.


Read More

iOS Get Space Remaining on Disk

So, you want to programmatically determine how much room is left on your iOS device, huh?

If you're writing an app that uses a lot of space on the device, its going to be nice to know how much room you have left, such as when you're recording audio via your app. I wrote a simple recording app that shows approximately how many hours are left of recording given the remaining disk space. That requires some knowledge about sampling rates and such, but all you really want is to get the space remaining on disk. I have just the ticket for that.

Here's an example of getting the file space remaining on your iOS device, which I use to great effect:


  NSError *err = nil;
  NSArray *nsSearchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  
  NSString *targetSearchPath = [nsSearchPaths lastObject];
  
  NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:targetSearchPath error: &err];
  
  if (dictionary) {
    NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
    uint64_t freeSpaceOnDisk = [freeFileSystemSizeInBytes unsignedLongLongValue];
  
    long kb = 1024ll;
    long mb = kb * kb;
  
    NSLog(@"%llu MB Free memory available.", (freeSpaceOnDisk/mb));
  
    // Now, do something interesting with this data
    
  } else {
      NSLog(@"Error %@", err);
  }

Well, that wasn't too painful at all, was it? When I found the answer originally, it took me quite a while to get there. Here's hoping you got there faster than me.

If you're an audiophile who hates cats, then you probably come here often because we like to listen to music too, and this is a cat-free zone. Internet high-five! You should come around here more often, which is why you should give us a +1, and we'll see you next time!


Read More

iOS How to Purge a Set of Core Data Entities

So, you want to remove all of one type of Core Data entity from your datastore/database, eh?

Sometimes you just want to clear out all your data, whether because the user is explicitly asking for it to be deleted, or as part of a simple wiping process during a server fetch (fetching to store locally) when you're dealing with small amounts of data. If you find yourself needed to delete all of your entities from a table in Core Data, it may surprise you how you have to go about it.

Here's an example:


+(void)deleteAllEventsInManagedObjectContext:(NSManagedObjectContext *)context
{
  // Create a NSFetchRequest to fetch Event entity objects
  NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];
  
  // Apply no filters, fetch them all
  request.predicate = [NSPredicate predicateWithFormat:@"1==1"];
  request.sortDescriptors = [NSArray arrayWithObject:nil];
  
  NSError *error = nil;
  NSArray *records = [context executeFetchRequest:request error:&error];
  
  // Write any errors to the console
  if(error){
    NSLog(@"%@", error);
  }
  
  // Iterate over the results, and delete them
  for(NSManagedObject *record in records)
  {
    // Delete by way of the NSManagedObjectContext it belongs to
    [context deleteObject:record];
  }
}

What surprised me the most was that it was necessary to fetch all the entities and then iterate over them deleting one by one. As far as I know, there continues to be no mass-destroy method in the SDK. On the plus side, this means you're forced to handle errors on a per-delete-basis that may arise from entity relationships-gone-bad, and I imagine that this is a good thing when your data model is more complex.

If you know of a better way, please leave it in the comments. And as always, please give us a +1 if you found this helpful to you.



Read More

Tuesday, December 17, 2013

iOS Run on Main Thread After Delay

So, you want to run some code on the main thread after a short delay, eh?


Sometimes we want to delay execution of code for a space, maybe because we want to put up a wait indicator and let the user know something interesting is happening. No matter your reasons, delaying the execution of code is often an acceptable way to get around issues[1]. Here's a quick example of how to accomplish this:

  int delaySeconds = 10;
  dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, delaySeconds * NSEC_PER_SEC);
  dispatch_after(delayTime, dispatch_get_main_queue(), ^(void){
    NSLog(@"This is running in the main thread after 10 seconds!");
  });

There you go, and best of luck to you on your journey!

[1] However, it can also be a signal of a poor implementation, so use such things as delaying code in a VERY sparing fashion.


Read More

iOS Setting Multiple Sort Descriptors

So, you want to have multiple NSSortDescriptors on your NSFetchRequest, huh?

So, you're using Core Data, and loving the power (and the limitations) that comes with it, and then you run up against the need to sort by two attributes in an Entity NSFetchRequest. How do you accomplish this? Well, by using an array of NSSortDescriptors, of course. But how do you us it? Well, how about this.

request.sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"last_name" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:@"first_name" ascending:YES], nil];

In this example, we're sorting by the last_name entity attribute, and then running a secondary sort by first_name. This will give us an order that looks something like this:

Cowen, Adam
Cowen, Paul
Cowen, Steve
Goldman, Peter
Goldman, Joseph
Welch, Barry
Welch, Joshua
Weiss, Daniel

If you need a full example of a NSFetch request with sort multiple descriptors, checkout our writeup here: Core Data NSFetchRequest with Multiple Sort Descriptors.

If you found this helpful, please consider giving us a +1, thanks!


Read More

iOS Pop to a Specific View Controller

So, you're in a NavigationController hierarchy, and you want to pop to a specific view controller in the hierarchy, huh?


Lets say you're in a NavigationController hierarchy, so views have been pushed one on top of the other, and you find yourself several layers deep in the view stack. How would one, for example, pop to the bottom element in the stack, or more interestingly, to the ViewController above the bottom view in the stack?

Here's a quick example for doing that:

  [self popToViewController:[self.viewControllers objectAtIndex:1] animated:animated];

But, that's not exactly what you're after, is it? You want to know how to pop to a specific view in the view stack, lets say, from the context of a ViewController and given its class name. We'll, heres how you can do that:

-(void)popToViewControllerWithClassName:(NSString *)viewControllerClassName
{
  Class targetClass = NSClassFromString(viewControllerClassName);

  // We're in a view controller in a navigation controller hierarchy, so we can just
  // get my UINavigationController thusly:
  UINavigationController *navigationController = self.navigationController;

  // Iterate over the list of viewcontrollers in this navigation hierarchy
  int indx = 0;
  for(UIViewController *viewController in navigationController.viewControllers){
    if([viewController isMemberOfClass:targetClass]){
      break;
    }
    indx++;
  }
  
  [self popToViewController:[self.viewControllers objectAtIndex:indx] animated:YES];
}

In brief, it creates a Class from the name you provide, gets the NavigationController, and iterates over the view stack until it finds the correct class... then it pops to that view in the stack. On the plus side, if the view is not found in the stack, the view will not pop (since its is effectively popping back to the current view).

If you found this helpful and think you might need this page again in the future, why not give it a +1, and we'll show up at the top of your search results.

Good luck on your journey!


Read More

iOS Get Bool from NSDictionary

So, you want to fetch and store a Boolean in an NSDictionary, huh?


NSDictionary objects are so awesome and useful. However, one thing that may not seem obvious at first is that NSDictionaries cannot store what are considered primitive types: int, float, double, as well as the scalar BOOL data-type. However, they can store objects like crazy. Most of the time, if we want to store a BOOL YES/NO value in an NSDictionary, we'll use NSNumber as an intermediary data-type like so:

  NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
  [dictionary setObject:[NSNumber numberWithBool:YES] forKey:@"myBooleanValue"];

Then, to fetch it back out again, and for the sake of explicitness, we can do this to get the value that we stored in the dictionary in the form of a BOOL:


  BOOL *myBooleanValue = [(NSNumber *)[dictionary objectForKey:@"myBooleanValue"] boolValue];

You may choose any intermediary type you'd like, but NSNumber is efficient and commonly used in this situation, so its recommended that you use this approach.

Best of luck on your journey.




Read More

iOS Get Class for String Name

So, you want to get a Class for a given String class name, eh?

If you're wanting to check the class type of an object, you first need to get the class in question so you can do things like invoking the "isKindOfClass" method. If you don't have a Class reference handy, but happen to know the name of the class, then you're in luck. This little bit of code here will give you back a Class and then you're in business:

  Class dictionaryClass = NSClassFromString(@"NSDictionary");


... well that wasn't so spectacularly hard or interesting, but what if we wanted to create an instance of the NSDictionary class (an object) from this, what do we do then eh? Well, we wrote about the answer here.

If that's all you needed, then best of luck on your coding adventure. Please do give us a +1 while you're here if you found this helpful!


Read More

iOS Core Data NSFetchRequest Sort Descriptors Example

So, you want an NSFetchRequest to return sorted data, huh?

We're on a tear with examples on NSFetchRequests. Our last few posts covered:


Here, we're going to revisit the multiple-sort-descriptors concept with a full blown fetch example. Here's how we would go about creating an NSSortRequest against a Person entity, and returning values by last_name, age order:

+(NSArray *)getEveryoneSortedByLastName:(NSString *)lastName andAge:(int)age inManagedObjectContext:(NSManagedObjectContext *)context
{
    // Create an NSFetchRequest for the People Entity
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];

    // Fetch all People
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"1==1"];
  
    [request setPredicate:predicate];
  
    // Sort first by last_name, then by age.
    NSSortDescriptor *lastNameSort = [[NSSortDescriptor alloc] initWithKey:@"last_name" ascending:YES];
    NSSortDescriptor *ageSort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
  
    request.sortDescriptors = [NSArray arrayWithObjects:@[lastNameSort, ageSort]];
    
    NSError *error = nil;
    NSArray *people = [context executeFetchRequest:request error:&error];
    
    return people;
}

Whew, so many NSFetchRequests posts... that's all for now.

If you found this helpful, please consider giving us a +1.


Read More

iOS NSFetchRequest with Predicates

So, you want to make an NSFetchRequest with NSPredicate filters, huh?

In a previous example, we showed you how to create and NSFetchRequest to fetch all of one kind of Entity. In this example, we'll show you how to filer your NSFetchRequest and pull in only entities that match certain criteria. Lets look at this example:


+(NSArray *)getEveryoneWithLastName:(NSString *)lastName andAge:(int)age inManagedObjectContext:(NSManagedObjectContext *)context
{
    // Create an NSFetchRequest for the People Entity
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];

    // Two predicate filters: last_name and age
    NSPredicate *lastNamePredicate = [NSPredicate predicateWithFormat:@"last_name = %@", lastName];
    NSPredicate *agePredicate = [NSPredicate predicateWithFormat:@"age = %d", age];

    // Build a compound predicate
    NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[lastNamePredicate, agePredicate]];
  
    [request setPredicate:compoundPredicate];
  
    // No sorting this time    
    request.sortDescriptors = [NSArray arrayWithObjects:nil];
    
    NSError *error = nil;
    NSArray *people = [context executeFetchRequest:request error:&error];
    
    return people;
}


Here you see we are using two filters and have put the whole fetch inside of a static method. I like to include entity-specific fetcher code inside of model categories, because its a nice way to compartmentalize model code.

If this example was helpful to you, please give us a +1, thank you!



Read More

How To Check if a NSString Contains Another NSString

So, you want to see if a string includes a given sub-string in iOS, huh?

NSRanges and NSString searches in iOS aren't the most fun thing to work with, fortunately there is a simple way to determine if a String contains another String in iOS, and it goes like this:

  NSString *interestingString = @"In the course of human events...";
  BOOL contains = ([interestingString rangeOfString:@"course"].location != NSNotFound);


Well, thank goodness that you don't need to iterate over matches, but if you do, we wrote about that too. Give us a +1 on Google, and we'll have your answer ready when you need it.



Read More

Monday, December 16, 2013

Run On a Background Thread in iOS

So you have some code that you want to run outside of the main thread in the background, eh?

Any long-running process, but especially those where you're connected to a remote server, will need to run in the background so as not to interfere with the user experience. The main thread needs to be left alone to handle things such as drawing the screen for the user and allowing user input, so how do we gin-up a background thread to handle our long-running processes?

  dispatch_queue_t backgroundProcessQueue = dispatch_queue_create("text.to.help.me.in.debug", 0);
  dispatch_async(backgroundProcessQueue, ^{
    NSString *requestURL = @"http://www.myserver.com/slow-api/run-slow-process";
    
    // Obligatory hand-wavy-remote-fetch
    NSDictionary *response = [FetchMasterGeneral runRemoteRequestAndGetResponse:requestURL];
    
    dispatch_async(dispatch_get_main_queue(), ^{
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"We're Back!" message:@"Whew! Sorry that took so long." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
      [alert show];
    });
  });

Bam, easy! Now you may want to display a wait message while you're running this background process (maybe not), and if you're interested in using one, I personally use the SVProgressHud plugin everywhere I run a background thread.

Best of luck on your adventure!


Read More

How to Thread Sleep in iOS

So, you want to pause the execution of a thread for a moment, eh?


Whether you're creating your own timer, or regularly checking on completion of another task before proceeding in some segment of code, you'll most likely find putting a thread to sleep is a good solution, if not the best solution for such circumstances.

You can put a thread to sleep in one of two ways:

// Until one minute from now
[NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow:60.0f]];

// Just sleep for 1 second

[NSThread sleepForTimeInterval:1.0f];

Now, you're on your way to snoozing your threads like the best of them.


Read More

iOS NSDate Beginning of Week

So, you want to get a NSDate object representing the beginning of this week, eh?


Well, how about a bit of code that will not only give you the start of the current week, but the week before and the week before that, as well as the weeks following? What do you say? If you're interested, this is how you do it:

  int weekOffset = 0;
  
  NSDate *rightNow = [[NSDate alloc] init];
  
  NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  NSDateComponents *calComponents = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:rightNow];
  
  // Current day of week, with hours, minutes and seconds zeroed-out
  int today = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:rightNow] weekday];
  
  [calComponents setDay:([calComponents day] - ((today) - 1) + (7 * weekOffset))];
  NSDate *startOfWeek = [cal dateFromComponents:calComponents];


In the above code, its the weekOffset integer that gives you the power for getting the start of weeks past and present. Set it to -1 for the beginning of last week, or 1, for the beginning of next week. A nice bit of code that will save you some frustration, I'll wager.


Read More

Saturday, December 14, 2013

How To Get The Current UIWebView URL

So, you've got a webview and you want to know what the URL it has loaded is, eh?

A webview is an iOS UI component that allows us to render HTML, whether fetched and loaded from a remote URL, pulled from the file-system, or manually (and arduously) created inline as a NSString or some such in your code. But, what if you load a remote URL and allow the user to click on links within the document, and they are subsequently directed to various pages on the web... if we wanted to check up on the user[1] and find out where they've gone, how could we do that?

So how do we tell what URL is currently loaded in our webview? We use what feels a bit like a trick, which is to ask the webview to evaluate some Javascript for us that will return the DOM window's current location.

  NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"window.location"];

Easy-peasy, and if you think about it, evaluating Javascript like this within the page opens up a lot of introspection opportunities. Now go forth and use this power for good.

[1] An aside, and not very important to this discussion: In my case I care about where the user goes after they are redirected from the authentication endpoint, since I use omni-auth on my server-side and redirect my users to authorize my app from there (rather than the typical case of saving authentication information local in my iOS app). So when they reach a success message, or a particular URL, I want to close the authorization screen. Works nice.



Read More

Thursday, December 12, 2013

Comparing Dates in iOS

So, you'd like to compare two NSDates in iOS, huh?

Date comparison is quite easy in Objective-C, but where it gets just a bit confusing is in the comparison result, which, when you are comparing two dates can be one of three values returned from the compare:(NSDate *)date method of NSDate: NSOrderedSame, NSOrderedAscending, and NSOrderedDescending.

Lets see a quick example:

  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateFormat:@"MM-dd-yyyy"];
  
  NSDate *date1 = [formatter dateFromString:@"01-01-2013"];
  NSDate *date2 = [formatter dateFromString:@"01-02-2013"];
  
  if([date1 compare:date2] == NSOrderedSame){
    NSLog(@"The dates are the same");
  } else if([date1 compare:date2] == NSOrderedAscending){
    NSLog(@"date1 is before date2");
  } else if([date1 compare:date2] == NSOrderedDescending){
    NSLog(@"date1 is after date2");
  }

>> date1 is before date2

And here it is in simpler terms (I think, at least), from the perspective of one of the dates:

[me compare:thatOtherDate];

NSOrderedSame - Me and that other date, we're the same.
NSOrderedAscending - I come before that other date.
NSOrderedDescending - I come after that other date.

I hope this helps you get things clear in your head, it certainly helps me to think of it this way.

Best of luck. And if you found this helpful, +1 this page, and it will be right at your fingertips to help you the next time you search for an answer to this question.


Read More

iOS Check if an Object Belongs to a Class

So, you want to tell if an NSObject inherits from a certain type of class, right?

Sometimes when dealing with abstract APIs, or after a night of exceeded the recommended amount of beer while coding, we find ourselves in the morning, headaches and all, dealing with collections of objects for which we'd really like to know their class type. Puritans of yesteryear perhaps would scoff at your untidy and drunken implementation, and cast askew glances at your choice of languages and their non-strongly-typed-collections, but you won't find any judging eyes here, no sir. 

Here's a couple of aspirin, and some short winded code that will help you check the class-type of any object that passes through your fingers:

  NSObject *obj = [NSObject alloc];
  if([obj isMemberOfClass:[NSObject class]]){
    NSLog(@"Its an Object!");
  } else{
    NSLog(@"Its NOT an Object! ... wait, how is that possible?");

  }

>> Its an Object!

So, this little bit of code above, that's good for knowing if the class type IS EXACTLY a NSObject class... but what if we just generally want to know if it has NSObject somewhere in its lineage? Well then, we need to whip out this dandy little method instead of the one above:



  NSObject *iAmAString = [NSString stringWithString:@"Who am I really?"];
  if([iAmAString isKindOfClass:[NSObject class]]){
    NSLog(@"Its an Object!");
  } else{
    NSLog(@"Its NOT an Object! ... impossibru!");
  }

>> Its an Object!

There you go, the ability to tell if a class IS A type of a certain class, and whether a class HAPPENS TO INHERIT FROM that class.

Go forth and drunken-code no more, but if you still need this post, give it a +1 and it will always be at the top of your searches. Good luck!


Read More

About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates