iPhone OS & SQL | SQL Code can be useful too in Objective-C

April 8th, 2010 iPhone SDK Tips

I use a special SQL class which takes all the heavy lifting out of programming a database in my iPhone and iPad applications. The library is called sqlite.h/m by Matteo Bertozzi. Its great, because a query can be executed in the following manner:

[sqlite executeQuery:@"SELECT * FROM test;"];

Here is a list of some of my commonly used SQL queries. (This will be updated over time)

//Select All rows from database ‘test’ where key=7. Limiting to 2 results
query2 = [NSString stringWithFormat:@"select * FROM test where key='%@' LIMIT 2",[tempA objectForKey:@"key"]];

//Search for Duplicates in database test where key is reused
select key, count (key) as NumOccurrences FROM test
GROUP by key
HAVING ( COUNT(key)>1)

//Update database ‘test’ setting key to a string where ClientProject = a string
query4 = [NSString stringWithFormat:@"UPDATE test set key= %d where ClientProject='%@'",generated,results4];

//Drop Table
[sqlite executeNonQuery:@"DROP TABLE test"];
//Create Table
[sqlite executeNonQuery:@"CREATE TABLE test (key TEXT NOT NULL, num INTEGER, value TEXT);"];
//Insert row into database
[sqlite executeNonQuery:@"INSERT INTO test VALUES (?, ?, ?);", @"hey", [NSNumber numberWithInt:42], @”"];

iPhone OS SDK – Searching for an item in an array

April 7th, 2010 iPhone SDK Tips

In my latest iPad application Design Brief, I required a way to search an array to check its contents for a value. I found this is how it is done.

NSArray *array = [NSArray arrayWithObjects: @"One", @"Two", @"Three", @"Four", nil];

for (NSString *element in array) {
if ([element isEqualToString:@"Three"]) {
NSLog(@”Found Three!”);
break;

}

}

The reference unfortunately alludes me, but it was a published book. If a commenter notes it, I will credit it.

iPhone OS SDK – Tableview Text and Subtitle with Image using Indent

April 6th, 2010 iPhone SDK Tips

Today I am posting something small which adds a great touch to a UITableViewCell. I would like to show you how to add an image to the left of a tableview cell, in the minimum amount of code (realistically) possible.

Firstly I am using the TableViewStyle UITableViewCellStyleSubtitle Which is great for a main row of text and a smaller row of text underneath.

UITableViewCellStyleSubtitle – Subtitle Row Style

First the visual output:
Screenshot2010-04-01at20.18.37.gA30siNRxbKg.jpg

and the code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @”CellIdentifier”;

// Dequeue or create a cell of the appropriate type.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

}

        cell.detailTextLabel.text = tempName;        
        cell.textLabel.text = tempProject;

}

But I would like to add an image to the left side. In the past I have Created three custom views ontop of each cell, and then for each cell, set a number of properties and inserted the text/image. This was all created and deallocated automatically.

I have found an even simpler way to do all of this. It uses the fantastic property ‘indentationWidth

UITableViewCellStyleSubtitle – Subtitle Row Style with Image

First the output pic:

ss2.tCfIZR4wjSgz.jpg

And the code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @”CellIdentifier”;

// Dequeue or create a cell of the appropriate type.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.selectionStyle = UITableViewCellSelectionStyleBlue;
                
                //Indentation Code.
                cell.indentationLevel = 1;
                cell.indentationWidth = 30;
                
                CGRect frame; frame.origin.x = 5; frame.origin.y = 5; frame.size.height = 32; frame.size.width = 32;
                
                //Print Icon
                UIImageView *imgLabel = [[UIImageView alloc] initWithFrame:frame];
                imgLabel.tag = 1000;
                [cell.contentView addSubview:imgLabel];
                [imgLabel release];        

}

        cell.detailTextLabel.text = tempName;        
        cell.textLabel.text = tempProject;

        //Setup Pic in Cell
        UIImageView *imageView = (UIImageView *) [cell.contentView viewWithTag:1000];
        imageView.image = [UIImage imageNamed:@"ico-project.png"]; // set the image for the imageview

}

This is a vast improvement to what I have previously used and have seen online.

I Hope this is found to be useful!

Announcing DesignBrief for iPad

April 2nd, 2010 iPhone SDK Tips

icon-512-nobg.mYreHvw0taww.jpg

My first iPad application Design Brief is now available for sale! Design Brief is based around the idea of asking a new client the right questions to generate a broad and descriptive design brief, either for a website or graphic designer.
The application was developed over 2 months and is a fantastic tool for a creative studio.

The official website is http://apps.duivesteyn.net/DesignBrief
The official twitter account is twitter.com/DesignBrief, but for support and all things de-apps twitter.com/de_applications should be used.
All feedback and comments received will be noticed, all problems will be replied to and all feature requests will be given consideration.

The initial sale price is just $2.49 available for the first 2 weeks only.

iPhone SDK In App Social Links

March 30th, 2010 iPhone SDK Tips

Screenshot2010-03-29at23.33.19.XD06TIrloGSP.jpg

Whilst we consider ourselves late on the ‘social’ scene, we have decided to add twitter and Facebook links, to us, from inside our apps only. We wish to do this with a small f and a small t button, generally on the about page. See the screenshot of our favorite 1-day project, SavingsGoal.

For usability, we didn’t simply want to just link to the URLS, first closing the app and then opening safari. We wanted to provide a good in app experience. This is why we chose to use PWWebViewController by matthiasplappert. This project creates a new view with a WebView all as a control. So the resultant code is only a few lines.
The result is a in app modular popup, which opens the facebook page, from within the application.

For the twitter button we could have done this too. But we had found something better. Oliver (aka @Dr_Touch) did a pretty nice twitter follow button code piece, which infact detects if any twitter client is installed on the iPhoneOS Device and then opens the twitter page for that user. It has a safe fallover, such that if no twitter client is installed, it then opens twitter.com in a webview.
Note: We did’t want the twitter link to open up straight away, we also wanted to alert the user that they are being taken out of the application.

The post for this code is at : http://www.drobnik.com/touch/2010/02/making-a-follow-us-on-twitter-button/

But of course, this post wouldn’t be complete without a code-sample! So this is how I wrote the social integration buttons, for our apps.

Firstly, add the following projects, and the #includes too.

Inline-Web-Browser: http://github.com/matthiasplappert/iPhone-Inline-Web-Browser
Olivers Twitter Code: http://www.drobnik.com/touch/2010/02/making-a-follow-us-on-twitter-button/

#import “PWWebViewController.h”
#import “deHelpers.h” //Note: This is a method which just has the above code by Oliver.

Then in viewDidLoad, I initiate the strings. Obviously you should change these to what ever you wish.

- (void)viewDidLoad {
//…
//Internet Links
websiteURL = @“http://apps.duivesteyn.net;
supportEmail = @“apps@duivesteyn.net;
facebookURL = @“http://www.facebook.com/apps/application.php?id=107880612574963;
twitterURL = @“de_applications”;
}

Then add the IBActions for the buttons:

#pragma mark -
#pragma mark Social Buttons

-(IBAction)openLinkFacebook{
[FlurryAPI logEvent:@“Pressed Link: Facebook”];
url = [NSURL URLWithString:facebookURL];
[self openURL];
}

-(IBAction)openLinkTwitter{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@“Twitter” message:@“Do you want to be taken to our twitter feed? \n\nThis will close the app.” delegate:self cancelButtonTitle:nil otherButtonTitles:@“No”,@“Yes”,nil];
[alert show];

}

- (void)alertView: (UIAlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex
{
NSLog(@“in alertView action, buttonIndex: %u”,buttonIndex);

if (buttonIndex==1) {                 NSLog(@“Open Twitter”);
//This is the Dr_Touch twitter follower code. I have just put it in a separate class, and I am calling it from there.
deHelpers *dehelper = [[deHelpers alloc] init];
[dehelper openTwitterAppForFollowingUser:twitterURL];

}
}

-(void)openURL{
NSURLRequest *request = [NSURLRequest requestWithURL:url];
PWWebViewController *webController = [[PWWebViewController alloc] initWithRequest:request];

UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:webController];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self
action:@selector(dismissModal)];
webController.navigationItem.leftBarButtonItem = cancelButton;
[cancelButton release];
[self presentModalViewController:navigationController animated:YES];         [navigationController release];

}

- (void)dismissModal
{
[self.modalViewController dismissModalViewControllerAnimated:YES]; }

And thats it for the code. Don’t forget to add the buttons to interface builder and then link the IBActions.

Hope you find it useful!

.

iPhone SDK | Run a method from a separate class

March 26th, 2010 iPhone SDK Tips

I often need to run code from a method which is in an alternative class (.m file if you will).
This is done with the following:


//Alert if in offline mode
deStockLookup *deStock = [[deStockLookup alloc] init];
gotInternet = [deStock checkInternet];

In This case, the output of the method checkInternet in the class deStockLookup is assigned to the variable gotInternet.

A simpler code snippet is running a method which takes no input or output. This would be done in the following:

deStockLookup *deStock = [[deStockLookup alloc] init];
[deStock checkInternet];

Notice that it is quite similar to how to call a method within the same class, which is done by:

[self localMethodName];

I use this code in almost every project and its one of those tricky little things I just needed on my site!

iPhone iPad SDK | Get Device Orientation

March 25th, 2010 iPhone SDK Tips


It may be useful to get the current orientation of the iPhone/iPad to then have custom code ran depending on the view.
A landscape and portrait UI are quite distinct and it would be common that orientation detection is used to perform tasks based upon the current orientation.


A quick way to get the current orientation is:

- (void)viewDidLoad {
[super viewDidLoad];

//The extra setup is not required for Portrait// if portrait set apprunning ==1
if(self.interfaceOrientation == UIInterfaceOrientationPortrait || self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@”apprunning”];
} else [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@”apprunning”];

Notice, this checks the orientation for UIInterfaceOrientationPortrait or UIInterfaceOrientationPortraitUpsideDown and then performs a task.

For reference, the Landscape Orientations are called: UIDeviceOrientationLandscapeLeft and UIDeviceOrientationLandscapeRight.

To add rotation support to a view controller, use the following method (this method is typically included already).

// Ensure that the view controller supports rotation and therefore show in both portrait and landscape.
– (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}

iPhone SDK Select Cell in Tableview

March 24th, 2010 iPhone SDK Tips

It may be useful to pre-select a cell in a Tableview in an iPhone/iPad app. As part of a persistent restore feature I am adding to an iPad application, I needed just the following code to pre-select the cell.

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
        self.title = @”Projects”;
        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
        

        NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
        [tableViewMaster selectRowAtIndexPath:scrollIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        [scrollIndexPath release];
        

}

This worked well for me, as generally when a cell is selected the correct connected code in the application also executes.

To get the correct indexPathforRow: value, I just used NSUserDefaults to store the last selected row. The NSUserDefaults variable is simply updated to the last selected indexPath.row in didSelectRowAtIndexPath

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

//Some Code :)

        [[NSUserDefaults standardUserDefaults] setInteger:indexPath.row forKey:@”LastTouchedContact”];
        [defaults synchronize];
        NSLog(@”Last Touched Client was: %d”,indexPath.row);

}

So now using the NSUserDefault state variable my viewWillAppear is updated to:

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
        self.title = @”Projects”;
        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
        
        int lastTouched = [[NSUserDefaults standardUserDefaults] integerForKey:@”LastTouchedContact”];
        
        NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:lastTouched inSection:0];
        [tableViewMaster selectRowAtIndexPath:scrollIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        [scrollIndexPath release];
        

}

iPhone OS SDK – UIAlert & UIAlert Action on button click

March 18th, 2010 iPhone SDK Tips

Using a UIAlertView in apps is very common and surprisingly complex. Its 2 lines, but comparing to VBasic its complicated. This is done by:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Welcome to Savings Goal” message:@”Please press the red button to setup your savings goal and current amount saved.” delegate:self cancelButtonTitle:nil otherButtonTitles:@”Ok Lets Save!”,nil];
[alert show];

These two lines I keep using over and over again. They form a very common copy and paste in my projects.
More interesting is performing an action on a button click in the UIAlertView. Lets say you have 2 buttons (buttonIndex 0 and 1). use the following method to execute code on that button press.

- (void)alertView: (UIAlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex
{
if (buttonIndex==0) {
NSLog(@”In AlertView Delegate”);
//start a timer
timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerVoid) userInfo:nil repeats:YES];
}

}

This will start a timer (NSTimer *timer), when the first button is pressed in an UIAlert. For UIAlerts with multiple buttons, you should use the int buttonIndex to detect which button was pressed.

Thats all for today, enjoy.

iPhone OS SDK – Contact Address Property

March 17th, 2010 iPhone SDK Tips

Today something quick. I’m working with addressbook information and I am extracting data from a contact, I already know I want in the addressbook (addressbookID=45 lets say).
How do I get their address?
And their Name, Company, Phone Number and Email!


Use the following.

NSLog(@”Looking Up Contact Now”);
ABAddressBookRef ab = ABAddressBookCreate();
ABRecordRef person = ABAddressBookGetPersonWithRecordID(ab,item2.integerValue);

NSLog(@”person: %d”,person);
if (person != nil) {

//Name
myName = (NSString *)ABRecordCopyCompositeName(person);

//Company
myCompany = (NSString *)ABRecordCopyValue(person, kABPersonOrganizationProperty);

//Email Address (this one is tricky)
ABMutableMultiValueRef emailMulti = ABRecordCopyValue(person, kABPersonEmailProperty);
NSMutableArray *emails = [[NSMutableArray alloc] init];
for (int i = 0; i < ABMultiValueGetCount(emailMulti); i++) {
NSString *anEmail = [(NSString*)ABMultiValueCopyValueAtIndex(emailMulti, i) autorelease];
[emails
addObject:anEmail];
}


if([emails count] > 0) myEmail = [emails objectAtIndex:0];

//Phone Numbers
ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSArray* phoneNumbers = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
CFRelease(phoneNumberProperty);

// Do whatever you want with the phone numbers
NSLog(@”Phone numbers = %@”, phoneNumbers);

//Location Address
ABMutableMultiValueRef addressMulti = ABRecordCopyValue(person, kABPersonAddressProperty);
NSMutableArray *address = [[NSMutableArray alloc] init];
int i;
for (i = 0; i < ABMultiValueGetCount(addressMulti); i++) {
NSString *city = [(NSString*)ABMultiValueCopyValueAtIndex(addressMulti, i) autorelease];
[address
addObject:city];
}
NSLog(@”addresses: %@”,address);

} else {
UIAlertView *baseAlert = [[UIAlertView alloc] initWithTitle:@”Address Link” message:@”Sorry, no address book link available” delegate:self cancelButtonTitle:nil otherButtonTitles:@”OK”, nil];
[baseAlert
show];
}