Posts Tagged ‘iphone’

iPhone SDK – Get Current Touch Location

April 16th, 2010 iPhone SDK Tips

Quick one today, I’m working on something new. It neeeded the last touch location to display some user input. It took me a little while to figure out how to call the location of the currently touched location, but its simple.

Just paste the following method into a viewcontroller:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        // get touch event
        UITouch *touch = [[event allTouches] anyObject];
        CGPoint pos = [touch locationInView: [UIApplication sharedApplication].keyWindow];
        NSLog(@”Position of touch: %.3f, %.3f”, pos.x, pos.y);
}

thats it! Check the Console/Log to see the output.
Note, using this over a tableviewcontroller is a different story, that is something I am yet to need, or figure out.

Screenshot2010-04-13at21.10.23.HdXB78fAPxSp.jpg

iPhone SDK – Animate button press (highlight) with alternate buttons

April 13th, 2010 iPhone SDK Tips

I was interested in implementing a simple button, which had a normal state and a ‘pressed’ or ‘highlighted’ state when being touched. I found an endless supply of lines of code, but after a little more playing around I found something new. And, it uses my fantastic principle of ‘simple’!

Firstly, what does the button look like? Its very simple really, its a modest edit button. The left image is the Normal state, the right button is for the highlighted state.

button-edit.aRIFeugod4Dy.jpgbutton-edit-toucheddown.j8VuddV07gAQ.jpg

And here is a (blurred) pic of the edit button in action, in my current development app. I did say it is modest.

Screen-shot-2010-04-07-at-23.31.28.ZpA61gVboFc3.jpg

So how is it done?

Well this one is 100% thanks to Interface Builder and it should be quite easy to follow.

Well, open Interface Builder, create a UIButton and add an Image to the button (as one normally would). See the below screenshot.
Screenshot2010-04-07at23.31.45.7ZbhOvcKdeMV.jpg

Now, Do you see where it says ‘Default State Configuration’ just under the ‘type’ setting? Press it

Screenshot2010-04-07at23.31.54.wVlfeQWuTcPN.jpg
We are now given 4 states where we are able to alter the button under, all without requiring any code at all!
Default State: Button is in its normal state
Highlighted State: Button is being pressed (this is the one we want)
Selected State: Extra code has registered this button as ‘active’ and so its in ‘selected’ mode
Disabled State: Extra code has registered this button as ‘disabled’ and so its in ‘disabled’ mode

So now I would go into ‘Highlighted State’ and just change the image, to the second edit image (see below).

Screenshot2010-04-07at23.31.56.WW7EQZ1udtpy.jpg

And thats it! No code at all. Build your app and test it!

Future Exercise:
Create the entire button without even the jpgs (Skill: Beginner)



Download: PSD Files (free for personal/commercial use)

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];
}

iPhone OS SDK – Checking Internet Reachability

March 16th, 2010 iPhone SDK Tips

Checking for an internet connection is becoming an important part of each iPhone app, as applications and websites evolve to more a more unified experience, getting info off the internet is very important.
Checking for an internet connection on iPhone can be a somewhat moderately difficult task. Luckily apple released a Reachability sample code, which then makes implementation very easy.
Well, in line with the recent theme of my site, I’m going to show you how I implemented it in my programming experiences lately.
I’m going to run you through I how do this in my apps, with a focus on keeping it simple.

Step 1: Add the reachability class from the Reachability Demo
Download them from the apple sample, or here. Then include them in your Xcode, by dragging the sources into xcode (Copying in is fine).

Step 2: Add the Extra Frameworks
Add the Foundation and SystemConfiguration inbuilt frameworks to your app.
Screen-shot-2010-03-16-at-10.37.42.CaUeN2xcbHVT.jpg
Step 3: Think first then code
iPhone-Empty-View-Implemented-by-Tapku.D6WKcx9GiT7b.jpg
The code is in the next step, but first its important to think where you are going to check for Internet Access. If you only need a particular site to work, change the initial ping to that one site. google.com, finance.yahoo.com etc.
econdly and more importantly, think about where you are going to implement the Reachability test. You will generally only want to do it once, in AppDelegate and then store the outcome as a boolean variable (YES/NO). If there ends up being multiple places in the application where you want to test for internet access, remember to do all the lookup business just once. This will speed up the app and also reduce app owners data transfer per session.
I am going to implement this such that a separate icon appears in the top right of my app MainView if there is no internet. Checkout the Three20 or Tapku empty pages, of how they implement the nice ‘empty’ screen which seems to be invented for iPhone by apple.

Step 4: The easy bit: The Code
I want to implement the reachability test in the appDelegate. First lets include the library in appDelegate.h (the header file).
#import “Reachability.h”

in the @interface of the header:
//Got Internets?
NSString *internetReachability;
BOOL gotInternet;

and in the bottom of the header, before end:

-(BOOL)checkInternet;

In the main of the appDelegate, we add a custom method to handle the work, it does most of the heavy lifting in the Reachability.m file. (Notice how the ping url is finance.yahoo.com. I recommend pointing this to the website you are interested in interacting with.
#pragma mark -
#pragma mark Checking Internet Connection

-(BOOL)checkInternet{
//Test for Internet Connection
NSLog(@“——–“);NSLog(@“Testing Internet Connectivity”);
Reachability *r = [Reachability reachabilityWithHostName:@“finance.yahoo.com];
NetworkStatus internetStatus = [r currentReachabilityStatus];
BOOL internet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
internet = NO;
} else {
internet = YES;
}
return internet;
}

This method is then able to be called where-ever, but I want to do it in didFinishLaunchingWithOptions. I use the following:
gotInternet = [self checkInternet]; //Test for Internet, calling the self method

if ( gotInternet == 0) {
//I have no internet
NSLog(@”hey, i have no internets”);
internetIcon.hidden = NO;

} else {
//I do have internet
NSLog(@”hey, i have internets: all systems go”);
}

4. And thats it!

Notice how it now stores the variable accessible class-wide. To check for internet now, just check to see the BOOL output of gotInternet. An extension to this is if there is no internet, show the Tapku empty window instead of something internet input related.

Heres the NSLog output, the second launch of the app I turned wifi on, on the mac.

Hope you found it useful, comments possible below.

iPhone SDK – Implementing the Tapku Graph In your application

March 7th, 2010 iPhone SDK Tips

One of the simpler and nicer available graph controllers your iPhone app is from the Tapku library. The tapku library is created by the team at http://tapku.com/ at hosted at http://github.com/devinross/tapkulibrary.

The graph view controller I find as a good mix between a simple SparkLine (http://key-solutions.ca/cksparkline.html) and the full-on core-plot.

Implementing the whole Tapku library is overkill to just use the chart and in fact can be a little difficult for beginners too.

To implement the graph follow the following steps:

Screenshot2010-03-08at10.05.25.OmxZv34TWnLc.jpg

1.Copy the following files out of the Tapku Library and copy into your project:

GraphController.h & GraphController.m
TKGraphController.h & TKGraphController.m
TKGraphView.h & TKGraphView.m
TKGlobal.h & TKGlobal.m
UIImageAdditions.h & UIImageAdditions.m
UIViewAdditions.h & UIImageAdditions.m
TapkuLibrary.bundle (for the graphics)

2. Add the framework QuartzCore

#import <QuartzCore/QuartzCore.h>


3. In GraphController.h, remove the line to import the full Tapku Library and import TKGraphController.h and TKGraphView.h.

Alter GraphController.h to:

//#import <TapkuLibrary/TapkuLibrary.h>
#import “TKGraphController.h”
#import “TKGraphView.h”


4. Now to call the graph, we display it as a modal view controller. Use the following code in your project to push the view onto the screen:

In your header file add:
#import
“GraphController.h”

In the main add

UIViewController *vc = [[GraphController alloc] init];

[vc setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[
self presentModalViewController:vc animated:YES];
[vc
release];
return;


And thats it!

I have a sample xcode project available too.

iPhoneOS iPad Development Resources

March 4th, 2010 iPhone SDK Tips

Code

General Cocoa Programming Resources


When in Trouble


My Favorite Libraries

  • Core Plot – Graphing Library
  • Three20 – The Famous Library with all the Facebook’y goodness
  • Tapku Library – An awesome set of tools – Nice Plot, Calendars, Loading HUD, EmptyView
  • Flurry – Awesome App Analytics
  • CKSparkLine – Basic Line Graph in a View
  • AppiRater – Add App Rating Reminder
  • Open Flow – Open Implementation of cover flow
  • InAppSettings – Include app settings inside the app easily
  • RegExKit – Objective-C Goodness


Address Book Integration


Email Integration


Useful Code


UI

UITableView Pretty Section Titles


Design


Sales

Application Sales Metrics

iPhone/iPad Development – Screen Rotation Resizing

March 3rd, 2010 iPhone SDK Tips

There comes a time in many apps where the screen will be rotated and the view will resize to the new screen layout. This will be even more important when it comes to the iPad which recommends that the app is usable on all different orientations.

On rotation, I call a method that then goes and tediously shuffles the frames of all my onscreen items for landscape, and then it needs to be done again when going back to portrait. (There should be a class out there somewhere which automates all this).

The important part is getting the X,Y,Width,Height data of all the frames of the objects and I have lately adapted code to generate the following:

if ([[self.view subviews] count] &gt; 0) { <br />
NSLog(@"Enumerating Subview Details\n%@",[self.view subviews]); <br />
}

<p>What is does is print (to NSLog) a list of all the subviews in the main view. It makes getting the frame X,Y,W,H data much faster. Hope it helps!</p>

iPhone UI – About Page Trends & Roundup

March 2nd, 2010 iPhone SDK Tips

iPhone about pages have become an art in theirselves. Below is a roundup of all the ones I’ve found interesting…More added as they come.

Some Simple iPhone UI Elements

March 1st, 2010 iPhone SDK Tips

I’ve been a little busy lately and have some ideas queued up but I havent had the chance to post much. Today something quick.

When developing my first app, I had some simple questions I could only answer by looking at what apps already do. Questions like “How is a single text field and keyboard on a page displayed to the user? How is a date best added/altered in a view? How can I enter in a full sized textbox for the user to enter a note? Insipration Source: Things from Cultured Code. They use some basic iPhone UI elements, but its just done so well.

iPhone OS Development – deSimpleChart

February 20th, 2010 iPhone SDK Tips

iPhone SDK Simple Charting Class

Throughout my current project I’ve been looking for a simple chart that I can place inside my iPhone Application. There is the best framework around core-plot, but I found is extremely complicated and a little unmanageable for experienced programmers. I then came across CKSparkLine which is a fantastic and simple way of plotting an array of data to a uiview.

In my work I have lead to a slightly adapted CKSparkLine which would be useful enough to help someone else who wants a simple chart plot in an iPhone App.

Introducing the sample code: deSimpleChart. A ’simple’ chart plot based  off CKSparkLine to help a programmer new to iPhone development out. Below a screenshot of the complete output of the application. Keeping the idea simple and easy to learn from.


deSimpleChart 0.01  
Build “Keeping charts simple”

Download at Github
->”git clone git://github.com/duivesteyn-enterprises/deSimpleChart.git”