Wednesday, July 21, 2010

Easy NSString substring

Sadly, creating a simple substring in Objective-C isn't quite as obvious as in other languages. Here's a basic method to grab a substring of a given string before a defined character, in my case the ":" character:

NSRange end = [_contentsOfElement rangeOfString:@":"];
[myVar setName:[_contentsOfElement substringWithRange:NSMakeRange(0, end.location)]];

If you wanted grab a string between two characters, you could do:

NSRange start = [_contentsOfElement rangeOfString:@"|"];
NSRange end = [_contentsOfElement rangeOfString:@":"];
[myVar setName:[_contentsOfElement substringWithRange:NSMakeRange(start.location, end.location)]];

Monday, July 19, 2010

UITextView automatic keyboard display

I've come across a few instances where my view is simply a UITextView for the user to enter some text into, such as for a comment field, or a twitter entry, etc. In these scenarios it is best to automatically show the UIKeyboard for the user to just start typing. This is a really easy one, all you have to do is have the synchronized UITextView become the first responder to make the keyboard appear:

- (void)viewDidLoad {
    [super viewDidLoad];
    [commentTxt becomeFirstResponder];
}

You can use the same technique with UITextFields too.

Friday, July 16, 2010

Deselecting UITableViewCell's when a view appears

Here's a simple tip to make your application look a little more polished. It's very common for us to push new view controllers when a row is selected in a UITableView. If the user uses a UINavigationBar button to go back to the previous view, or the new view controller gets popped in some other manner, you will want to remove the highlight from the selected UITableViewCell. Here's a simple snippet to add to do just that assuming you have a UITableView that is an IBOutlet on your view controller:

- (void) viewDidAppear:(BOOL)animated {
if ([self.table indexPathForSelectedRow]) {
[self.table deselectRowAtIndexPath:[self.table indexPathForSelectedRow] animated:YES];
}
}

Facebook API Integration on the iPhone

This is another short post, for I can't take credit for any of the code. I just wanted to pass across a link to the Facebook iPhone SDK that they've put together. I despise Facebook, but must admit this is one of the most well polished and documented libraries for the iPhone that I've seen yet. The framed webview that pops up for the authorization looks great.

Thursday, July 8, 2010

Default UITableViewCell font, and how to change it

The default font is... Helvetica! If you want to change the size of the font, you can use:

cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:14.0];

You can also change the font using the above statement with a different font name.

Hiding the keyboard when using UISearchBar and UITableView

In one of my recent applications, I set up a UIViewController containing a UISearchBar and a UITableView. I implemented all the necessary delegate methods for both classes, and my search was working just fine (after working out a few kinks..). I did have one remaining problem though... Since I was searching as the user was typing, similar to an autocomplete on the web, the results were automatically being shown in the tableview but the keyboard was still there! This only showed the user a few results and was not very user friendly. I next figured out how to hide the keyboard once the user touched the tableview and started scrolling.

It's actually really easy to do this - all you have to do is implement the UIScrollViewDelegate as follows:

@interface YourViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

...and then put the following into your class.m source:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[search resignFirstResponder];
}

HTTP Basic Authentication on the iPhone

I can't steal credit for this one. I just wanted to pass along this excellent link to a post titled Objective-C and HTTP  Basic Authentication. It still amazes me that the iPhone SDK doesn't have base 64 encoding built in... but at least some smart folks out there have gone through the trouble of putting it together for us.

What I ended up doing was putting the encode function in my parent REST client class, then I was able to call it as necessary in my subclasses.

NSURLErrorDomain error -1012

So have you run across this one when trying to issue some url requests? What it means is there was an authentication error - NSURLErrorUserCancelledAuthentication. Okay, so what does that mean? You likely are trying to issue a synchronous http request and not passing proper authentication, or you've messed up your auth in some other manner. It's a lot easier to handle authentication when using asynchronous calls and responding to the auth challenge:

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential;
        newCredential=[NSURLCredential credentialWithUser:@"username"
                                                 password:@"password"
                                              persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

Changing UITableViewCell text colors

This is a really easy but, but may not be immediately apparent. Personally, I first tried changing the color of the cell directly, then tried changing the color of the text within the cells. What you actually need to do is change the textColor property of the UILabel's that are inside of the cell. For example, if you want to change the color of the textLabel, you would use:

cell.textLabel.textColor = [UIColor lightGrayColor];

The same goes for the detail label if you are using that type of cell:

cell.detailTextLabel.textColor = [UIColor blackColor];

Sunday, June 13, 2010

Declaring constants in Objective-C

Yes, I'm back! Sadly my last post was in January, but I'm hoping to get back on the wagon here adding tips and tricks. Today I'll bring you the rather simple task of declaring and using constants in Objective-C. Let's assume you want to declare an NSString constant in your class that holds a url. In your header .h file you will need the following:

#import 

extern NSString * const BaseURL;

@interface ClassName : NSObject {

You will then need to set it's value in your main .m file as follows:

#import "ClassName.h"

NSString * const BaseURL = @"http://some.url.com/path/";

@implementation ClassName

You can now access this constant throughout your class or subclasses. Here's an example of usage:

NSString *urlString = [NSString stringWithFormat:@"%@%@", BaseURL, @"filename.html"];