Archive

Posts Tagged ‘iPhone’

SQLite Wrapper

April 20th, 2010 No comments

I created this code a while back when I was still targeting older iPhone OS i.e. 2.0 and above. I’ve found really useful when I need to throw things at a local SQL database on the device, since it’s creation I’ve moved up to target OS 3.0 and above only. Though I’ve migrated my latest app to these later targets I still have yet to migrate the database code over to user Core Data. :( It’s just not a priority and using the SQLite database directly still works perfectly on the later OS versions, though I would really like to get the benefits of using Core Data. Ah well maybe version 1.1 of the application.

The wrapper is written in c++ as I felt it was more kind to the usage of the SQLite API plus I ended up move the core of the original project that the code came from over to c++ due to performance issues (it was doing a lot of work and an iPhone is not my macbook).

//
//  Database.h
//
//  Created by Robert on 20/07/2009.
//  Copyright 2009 Electric TopHat Ltd. All rights reserved.
//

#import
#import

// ---------------------------------------------
// Database Access Class
// ---------------------------------------------
class Database
{
#pragma mark ---------------------------------------------------------
#pragma mark === Constructor / Destructor Functions  ===
#pragma mark ---------------------------------------------------------
public: // Functions

// ---------------------------------------------
// Constructor
// ---------------------------------------------
Database( NSString * _name, NSString * _createString = nil );

// ---------------------------------------------
// Destructor
// ---------------------------------------------
~Database();

#pragma mark ---------------------------------------------------------
#pragma mark === End Constructor / Destructor Functions  ===
#pragma mark ---------------------------------------------------------

#pragma mark ---------------------------------------------------------
#pragma mark === Public Functions  ===
#pragma mark ---------------------------------------------------------
public:

// ---------------------------------------------
// execute a single sql statement
// ---------------------------------------------
Boolean execute( NSString * _sql, NSMutableArray * _results = nil );
Boolean execute( NSString * _sql, NSMutableDictionary * _result );
// ---------------------------------------------

// ---------------------------------------------
// Table has Column
// ---------------------------------------------
Boolean hasTableColumn( NSString * _tableName, NSString * _columnName );
Boolean tableColumns( NSString * _tableName, NSMutableArray * _results );
// ---------------------------------------------

// ---------------------------------------------
// Alter the table
// ---------------------------------------------
Boolean updateTable( NSString * create, NSString * insert, NSString * _name );
// ---------------------------------------------

// ---------------------------------------------
// Return the error string
// ---------------------------------------------
NSString * error() { return m_error; };
// ---------------------------------------------

#pragma mark ---------------------------------------------------------
#pragma mark === End Public Functions  ===
#pragma mark ---------------------------------------------------------

#pragma mark ---------------------------------------------------------
#pragma mark === Private Functions  ===
#pragma mark ---------------------------------------------------------
private: //Functions

Boolean createWithBundleDatabaseWithName(NSString* _name);
Boolean createAnEmptyDatabaseWithName(NSString* _name, NSString * _createStatement);

#pragma mark ---------------------------------------------------------
#pragma mark === End Private Functions  ===
#pragma mark ---------------------------------------------------------

#pragma mark ---------------------------------------------------------
#pragma mark === Protected Data  ===
#pragma mark ---------------------------------------------------------
protected: // Data

// -------------------------
// Error String
// -------------------------
NSString *		m_error;
// -------------------------

// -------------------------
// sql database
// -------------------------
sqlite3 *		m_database;
// -------------------------

#pragma mark ---------------------------------------------------------
#pragma mark === End Private Data  ===
#pragma mark ---------------------------------------------------------

};
// ---------------------------------------------

The above API is very simple or I hope it is. The basic idea is to provide a minimum wrapper round the core SQLite API though later on I did end up providing an additional helper function ‘updateTable‘. So what goes on?

Construction

The class constructor takes a ‘name‘ and an optional sql command, the ‘name’ is the name of the database file that will be created on disk. The first time you construct the database class it will first try to copy a database of the same name from your application bundle onto the disk, if the database file is not found in your bundle it will create one and optionally run an sql command (this can be used to create the desired table structure). The second time you construct the database class it will use the RW database contained in the applications working directory.

Execute

The class provides a very simple interface to run SQL commands, just create a string and call the execute command. You can optionally provide a mutable dictionary or a mutable array to return data from the database. Note that the array will contain a dictionary for each row provided and the key values are those requested in your sql statement  or the column name.

Helper Functions

The class provides a few little helper functions:

  • hasTableColumn : has the table got the column.
  • tableColumns : return all the table columns associated with a table.
  • updateTable : this can be used to make changes to your table (though I will need to document it more sorry).

WARNING : If you want to include c++ class’s in your project you must change the .m file extension to .mm this will inform the compiler that you are using Objective-C++ else you will get a lot of compile errors.

I’ve tried to keep it simple, so if you know how to write SQL statements and don’t want to worry about the low level API or C++ just scares you then hopefully this is for you. As always the code is as is and use it at your own risk, feel free to alter, hack or otherwise distribute the code and if you have any questions please feel free to get in touch.

Download : Database.hDatabase

Sample Project : SqliteDBWrapperSample

Thanks for reading.

iPhone Date Range Editor

February 19th, 2010 1 comment

Date range editing is a useful when dealing with calendars or time periods, the iPhone calendar provides a nice simple way of editing a date range. Just open up the Calendar hit the + button and edit the events date range, you get a lovely screen that looks like the image below:



Calendar Date Rang Editor

Unfortunately UIkit does not provide a basic control to edit a date range editor, it does provide the UIDatePicker which can be used to build your own date range editor and this is what I have set about to do. The basic idea is to emulate the basic functionality implemented in the calendar date range editor, i.e. The start and end dates can be selected which in turn alters the date displayed in the UIDatePicker and the control provides basic error detection changing the start date red when invalid and prevent savings if there is an invalid date range.

The following is the result of my attempt to recreate this control in a simple and customisable way, the header file below is rather long but there are only a few items exposed to interface builder to make it easy to setup.

//
//  UIViewControllerDateRangeEditor.h
//  UIViewControllerDateRangeEditor
//

#import

@interface UIViewControllerDateRangeEditor : UIViewController
{
@private

// ----------------------------------------
// control objects
// ----------------------------------------
IBOutlet UIBarButtonItem *	leftBarButton;          // Navigation Button to be used on the left    : Cancel
IBOutlet UIBarButtonItem *	rightBarButton;      // Navigation Button to be used on the right  : Save
// ----------------------------------------

// ----------------------------------------
// Display Content
// ----------------------------------------
IBOutlet UILabel  *			startLabel;                   // start label : used for highlighting and is not altered
IBOutlet UILabel  *			startDate;                     // start date label : used for highlighting and contains the current start date

IBOutlet UILabel  *			endLabel;                     // end label : used for highlighting and is not altered
IBOutlet UILabel  *			endDate;                      // end date label : used for highlighting and contains the current end date
// ----------------------------------------

// ----------------------------------------
// control objects
// ----------------------------------------
IBOutlet UIDatePicker *		datePicker;       // date picker : link the value change to the dateChanged action
// ----------------------------------------

// ----------------------------------------
// Start Date Colors
// ----------------------------------------
UIColor *					normalColor;
UIColor *					highlightColor;
// ----------------------------------------

// ----------------------------------------
// Buttons
// ----------------------------------------
IBOutlet UIButton *			buttonStart;              // button that is to be highlighted at the start
UIButton *					buttonSelected;
UIImage  *					buttonImage;
// ----------------------------------------

// ----------------------------------------
// Date Formatter
// ----------------------------------------
NSDateFormatter *			dateFormatter;
// ----------------------------------------

// ----------------------------------------
// current dateValue
// ----------------------------------------
NSTimeInterval				startTimeInterval;
NSTimeInterval				endTimeInterval;

NSTimeInterval				minTimeInterval;
NSTimeInterval				maxTimeInterval;
// ----------------------------------------

// ----------------------------------------
Boolean						editingStartDate;
Boolean						savePressed;
Boolean						delayReset;
// ----------------------------------------
}

@property (nonatomic) NSTimeInterval startTimeInterval;
@property (nonatomic) NSTimeInterval endTimeInterval;

@property (nonatomic) NSTimeInterval minTimeInterval;
@property (nonatomic) NSTimeInterval maxTimeInterval;

@property (nonatomic, readonly) Boolean savePressed;

- (void) reset;

- (IBAction) cancel:(id)sender;
- (IBAction) save:(id)sender;

- (IBAction) dateChanged:(id)sender;

- (IBAction) selectStartDate:(id)sender;
- (IBAction) selectEndDate:(id)sender;

@end

The View controller provided with this article should permit you to create your own custom date range editor using interface builder, this can either be loaded manually or via the main nib. The sample project provide demonstrates how the view controller is setup and how you can use it in your own project.



Sample Images

Download : UIViewControllerDateRangeEditor.h, UIViewControllerDateRangeEditor.m

Sample Project : UIViewControllerDateRangeEditor

Example Usage :


// -------------------------------------------------------------------
// load  the date range editor and push it onto the view stack
// -------------------------------------------------------------------
- (IBAction) editDateRange:(id)sender
{
if ( editor == nil )
{
editor = [[UIViewControllerDateRangeEditor alloc] initWithNibName:@"UIViewControllerDateRangeEditor" bundle:nil];
editor.title = @"Edit";
}

editor.startTimeInterval = startTime;
editor.endTimeInterval   = endTime;

[[self navigationController] pushViewController:editor animated:TRUE];
}

// -------------------------------------------------------------------
// when the controller returns from the editor copy the date out if save has been
// pressed and reset the controller.
// -------------------------------------------------------------------
- (void) viewWillAppear:(BOOL)animated
{
if ( editor )
{
if ( editor.savePressed )
{
startTime = editor.startTimeInterval;
endTime = editor.endTimeInterval;
}

[editor reset];
}
}

As always the source is provided as is and use it at your own risk, feel free to alter and extend as you see fit. Have fun.

Loading from a nib

February 3rd, 2010 No comments

Interface builder is a great tool provide with the xCode and I make good use of it when building iPhone projects, if you are scared by this Tool please take the time to play or watch some of the many tutorials online. I started using during my first iPhone project and I have not looked back since. l usually build basic / functional user interfaces, then handing it over to a proper designer / artist to change coder art into a work of beauty. It has really helped our development process, as I can try and concentrate on product functionality and not worry so much about how it looks. Though there I must admit that there is always a bit of too and fro that must be done, as lots of things it is not a one way street.

In the past I’ve split a project into several nib’s each one containing a one or more views and a single Controller object, this permits functionality to be split and sectioned easily. Having multiple nibs also reduces the lightly hood of trashing others work and limit bugs to a particular area.

In the latest project I have had to take one step further where a nib can contain a single view, this permits the same view higher-archy to be constructed multiple times (such as for a table view).

It’s so easy to use nib’s and decode / load them multiple times. The usual way to load a nib is using the view controller function initWithNibName:bundle: but in some cases you don’t want to construct a view controller, you really only want the view. Well the easies way round that is to load the nib using the NSBundle, this will provide an array of constructed objects (UIView, NSObjects, etc). This is really simple as the code below demonstrates.

// -----------------------------------------------------
// Load the first view from the nib
// -----------------------------------------------------
+ (UIView*) loadFirstViewFromNibName:(NSString*)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
	NSBundle * bundle = ( nibBundleOrNil ) ? nibBundleOrNil : [NSBundle mainBundle];
	NSArray * nib = [bundle loadNibNamed:nibNameOrNil owner:self options:nil];

	for ( NSObject * obj in nib )
	{
		if ( [obj isKindOfClass:[UIView class]] )
		{
			return (UIView*)obj;
		}
	}

	return nil;
}

Note : You will still need to retain the returned object.

Loading stuff from a nib in this way has great potential, I use this method to load individual UINavigationControllers when I want to branch the navigation off and return to the same point in the previous navigation controller. You branch of like this using the presentModalViewController function and dismissModalViewControllerAnimated to return. The code snippet below shows the simple alteration need to load a navigation controller.

// -----------------------------------------------------
// Load the first navigation controller from the nib
// -----------------------------------------------------
+ (UINavigationController*) loadNavigationControllerFromNibName:(NSString*)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
	NSBundle * bundle = ( nibBundleOrNil ) ? nibBundleOrNil : [NSBundle mainBundle];
	NSArray * nib = [bundle loadNibNamed:nibNameOrNil owner:self options:nil];

	for ( NSObject * obj in nib )
	{
		if ( [obj isKindOfClass:[UINavigationController class]] )
		{
			return (UINavigationController*)obj;
		}
	}

	return nil;
}

Just some small code snips this time, but as always please feel free to use and alter as you see fit. If you have any questions please leave a comment or get in touch by other means. Thanks.

iPhone YouTubePlayer

December 18th, 2009 2 comments

youtubeI’ve been plodding away on a project (it’s getting there almost) and one of the things that I really wanted was to provide video tutorials for the user. I really don’t want to package all these videos with the application, really once you’ve watched them once you will probably never look at them again (If I’m wrong about that let me know ).

The new idea is to stream them down to the device, once option was to use the MoviePlayer provided with the sdk. This is fine if you want to host your own video content, but I’m not that confident that I would be able to provide a reliable content service. Whats the alternative then, well there is always  YouTube and the iPhone has a compatible way of playing back videos even inside the application. Unfortunately to play these YouTube videos you need to use a UIWebView where the simplest version of a player would present the user with a link to play the video. Not the most elegant solution but it works, but I was not really happy with the solution.

I decided I could do better, I really wanted a player that provided complete application integration and the resulting Player is just that. The player is easy to use and has simplest API I could come up with, it’s also very easy to integrate with any application. Go on and try it out.

//
//  YouTubePlayer.h
//
//  Created by Robert on 18/12/2009.
//

#import <Foundation/Foundation.h>

@interface YouTubePlayer : NSObject <UIWebViewDelegate, UIAlertViewDelegate>
{
@private
	UIView	  *				  background;
	UIWebView *				  webView;
	UIActivityIndicatorView * activityIndicator;
}

- (void) playbackVideo:(NSString*)_videoID InView:(UIView*)_view;

@end

Example use:

// Inside a UIViewController
- (void) play
{
     // create the video player object
     if ( videoPlayer == nil )
     {
           videoPlayer = [[YouTubePlayer alloc] init];
     }

    // Request the video to be played using the video id
     [videoPlayer playbackVideo:@"MuU00Q3RhDg" InView:self.view];
}

As always the source is provided as is and use at your own risk, also feel free to alter and use as you want I don’t mind. Have Fun.

Download : YouTubePlayer.h, YouTubePlayer.m

Note: You will need to include the SystemConfiguration framework as this is used to check for the availability of a web connection.

Thanks to the following resources that make it possible to build this player:

Line Graph

November 17th, 2009 No comments

linegraph I did some work a couple of weekends ago where I implemented a basic line graph view for the iPhone, the code is now up and available. I don’t think it’s the best implementation in the world and it sure as hell could do with some improvement, but I think that of all the code I write :) Oh well the current implementation works for me at this time, but feel free to grab the code and alter it to your own needs.

Categories: Code Tags: , , ,

iPhone Bar Graph

October 19th, 2009 No comments

Over the weekend I managed to throw together some code to produce a reasonably pretty bar graph using Objective-C and a UIView base class. The Graph is rendered via the drawRect function and uses the CGContext to render the graph and all it’s components.




BarGraphPic1BarGraphPic0


Current Features:
• Positive Graph Rendering.
• Positive / Negative Graph Rendering.
• Customizable Bar rendering.
• Customizable Graph area rendering.
• Background Image support.
• Font selection.
• Hide / Show Labels.
• Hide / Show bar names.
• Hide / Show Scale.
• Hide / Show Bar Percentages.



The graph code still need’s some work, here is a few ideas on what I would like to improve, reduce the complexity of the drawRect function, add support for negative value graphs. I would also like to provide a number of render option (2D / 3D) that could be selected via an enum value rather than the current set of booleans (there are quite a lot of them).



Update: Look’s like my percentage calculation could do with some work as well :)

Categories: Code, Work Tags: , , ,

AD-HOC Automation

October 13th, 2009 No comments

AutomatorI recently had a lot of trouble with building and distributing AD-HOC builds, with that in mind I set out to not to fall into the same trap twice (lots of time wasted) and automate the process using a shell script.  This would be able to compile the desired build configuration, grab any documentation I wanted to go along with said build and include a valid mobileprovision (preferable the one it was built with). The script would then package up all this data into an object that could be directly distributed to the test group.

The result is a simple script that you can download it here.

I struggled with the selection of the correct mobileprovision, I initially had the provision file in the project and just directly copied it, which worked fine for a while. I then ran into the problem of having to remember to update it when adding another device to the provision (after I copied to the organizer I would also have to update all my projects). The solution that I ended up using, was to use grep to search the provision folder for the name’s contained inside mobileprovision file and then copy that one into the output folder. It’s not a perfect solution but better than having two copies of the provision lying around, one in the project and another in the directory used by the Organizer. If you would like to use the script please feel free (you will need to alter it slightly for your project). I am in the process of writing up some simple steps on how to integrate the script into your xcode project, they should be up soon.

Note : The Package script creates both a zip and a dmg, they both contain the same information I did it just for completeness.

[UPDATE :: Setup Instructions can be found here]

iPhone Ad-Hoc Hell

October 9th, 2009 No comments

Like most developers working on the I phone I’ve had the distinct pleasure of trying to get an Ad-Hoc build working. Dave managed to do this with Brett Nova without much issue, unfortunatlly when I tried to get this all working for Prok I ran into hell where the build would work locally but as soon as I sent it out to the rest of the team to play with it failed.

The Setup:
1) Copy the Release Build.
2) Add an Entitlements file (from Add New File).
3) Un-tick the Entitlements tick box.
4) Add the Entitlements file into the build configuration.
5) Select the Ad-Hoc Distribution profile in the build configuration.
6) Hit build (remember to select the correct platform).

Once this was all done I checked the Build Results for the embedded mobileprovision and profile, yep they where all there. I eventually concluded (after repeating the steps several times) that the build set up was fine so it must be something else, but what.

Next Step:
I checked the devices I added in the developer connect web site as it could be huyman error. I ask the guys to re-send there device UIDD so I could check them against the devices added, they where fine? What the hell was I doing wrong it just did not make any sense. They could install the mobileprovision but the app would always fail to launch?

Finally:
After going back to the drawing board and hitting my head off a brick wall for a couple hours, I decided to get two machines, two devices to see if I could replicate the issue locally. I would build the app on one machine pass it to the other and try to install the build in the same way the users did and hey presto the build failed to run. The build worked on the machine that it was compiled on but not once I transferred it to the other (I did this vice versa and got the same results), it must have been my distribution method. We were using drop box ( which is great ) to share data and files and at the time I was just dropping the .app directly and not zipping it as recommended in the documentation. Much like svn drop box is adding hidden files into the directory structure and as the .app container is a wrapper round a directory hidden files were being added to the container which altered the application causing the licencing to fail.

Conclusion:
Follow the apple steps to the letter and should all be fine (and don’t waste lot’s of your own time like I did).

Categories: Rants, Tools Tags: , ,

Modulo in the Charts

May 28th, 2009 1 comment

modulo

It seems that everything has happened at once, which is a bit of a shame because it makes the number analysis a bit difficult to understand. Right now Modulo is featured on the front page of the UK App Store, it can also be seen on the Canadian, German, Austrian stores as well. The feature has driven sales up in those territories, can we make a living yet? Probably not.


What’s happened?


• Modulo was featured last week world wide in the New and Noteworthy under the Games category, which gave us a small increase in sales in the UK and US. Not massive number but better than what we were doing.

• Apple contacted us and asked us to remove the Sale sticker plastered over the front of our Icon as they were thinking about doing a feature for our app, we complied and wondered what was going on.

• Modulo disappeared from the Games New and Noteworthy’s front page, it’s still there. You have to dig one layer down to find it now and our sales dropped off again.

• Modulo Appeared on the App Store Front Page in the UK store and sales in that territory have increased and the application has climbed the UK chats.


modulo-at-46modulo-at-28modulo-at-no-8



This morning Modulo was sitting at 46, 28 and 8 on three separate UK pages, it will be very interesting over the next few days to see what else happens.

Can Modulo break into the US charts? I have no idea, but I feel that it need to be there as well.

Categories: News Tags: , , ,

Modulo

April 24th, 2009 No comments

icon_512_roundedwhiteIntroducing Modulo

Ok a few days late but we submitted our third game this week, wednsday to be precise. It’s an original puzzle game designed by Dave and is slated for release to the App Store on the 29th of April. So far the guinea pigs that played enjoy it so much I have to fight to get my iPhone back.

We are starting to try and promote the game so watch out and I’ll post a video of the game on our YouTube channel very soon. Modulo screen shots are up on our FaceBook page so go and check them out.

Categories: News Tags: , , , ,