Tumblelog by Soup.io
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

April 20 2010

iPhoneOS SDK – iPad Design Template – Multiple Views with Group Table View as the Master View Controller

Here’s my favorite iPad Project Template. Modified for 6 view controllers, split view, master tableview uses sections, and is in group format!

Screenshot2010-04-14at18.03.13.kPF6RWxDwfm2.jpg

Reposted byjalakam jalakam

iPhoneOS SDK – Subclassing a UITableview

This is more of a personal reminder about how to subclass a UITableViewCell, but this should be useful to the discerning reader. All the edits required to subclass are the lower code line in each section, the above is the default code (commented out).

.m file Modifications

#import “UITableViewCellFixed.h”

// Below is first the original then the subclassed
        //UITableViewCell *cell = [tableview dequeueReusableCellWithIdentifier:CellIdentifier];
        UITableViewCellFixed *cell = (UITableViewCellFixed *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
if (cell == nil) {
                
// Below is first the original then the subclassed
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
cell = [[[UITableViewCellFixed alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
                
                
//Cell Accessories
                //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
                

}

Then the subclass file looks like:

// UITableViewCellFixed.h
//

#import <UIKit/UIKit.h>

@interface UITableViewCellFixed : UITableViewCell {

}

@end

//
// UITableViewCellFixed.m
//

#import “UITableViewCellFixed.h”

@implementation UITableViewCellFixed
- (
void) layoutSubviews {
        [
super layoutSubviews];
        
self.textLabel.frame = CGRectMake(self.textLabel.frame.origin.x,
4.0,
self.textLabel.frame.size.width,
self.textLabel.frame.size.height);
        
self.detailTextLabel.frame = CGRectMake(self.detailTextLabel.frame.origin.x,
                                                                                        
8.0 + self.textLabel.frame.size.height,
                                                                                        
self.detailTextLabel.frame.size.width,
                                                                                        
self.detailTextLabel.frame.size.height);
}
@end

April 16 2010

iPhone SDK – Get Current Touch Location

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

April 14 2010

iPhoneOS SDK – iPad Popover Controller

The iPad Popover control is possibly the least publicized feature of the iPhoneOS SDK, but becomes critical to in app actions and workflows. This is because the Popover Controller can show a small UIView of controls and more importantly save the user from having the whole screen change navigation hierarchy. A simple popover for example, can be used to edit a textfield, or change a date really quickly. In an iPhone app, this would typically be done by sending the user to a ‘DetailView’ where the setting/property can be change, whereas on the iPad this is highly discouraged.
I am going to go through a quick popover example today, and on monday I will post a fantastic iPad user template.

1. Understanding the context
First, you need to know where a popover should be used. I can’t say much more than whats above. Use the apple apps, use the other top 100 apps, see how they use the popover controller. This will give you a feel of what it should do.
2. Some Code
Firstly, your main view controller {.h} needs a <UIPopoverControllerDelegate> declaration.
In your main view controller, add the following to the @interface (.h file)

        //PopoverViewController
        UIPopoverController *popoverController;

and just before @end add an IBAction:
- (IBAction)popOverViewCall:(id)sender;

Create a New View & ViewController {.h/.m} files and place them in your project. This is the actual popover that will come up. Place controls how ever you see fit.  I call this popover controller MyViewControllerForPopover. Add an include of this file to your main view controller, eg:
#import “FirstDetailViewControllerPopOverControl.h”

In MyViewControllerForPopop {.m file}, add the following code:
-(void)viewDidAppear:(BOOL)animated
{
        
self.contentSizeForViewInPopover = CGSizeMake(320,320);
        
}
This sets the size of the popover for showing.Go into interface builder and add a couple controls to ensure you know when it works.
And finally in your main view controller {.m file}, add the IBAction:

-(IBAction)popOverViewCall:(id)sender{
        
FirstDetailViewControllerPopOverControl *myViewControllerForPopover = [[FirstDetailViewControllerPopOverControl alloc] initWithNibName:@”FirstDetailViewControllerPopOverControl” bundle:nil ];
        
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:myViewControllerForPopover];
self.popoverController = popover;
popoverController.delegate = self;
        
        [popover
release];
        [myViewControllerForPopover
release];
        
        
CGPoint point = {200,200}; // Place to put on screen
        CGSize size = {600,600}; // A content range (see apple docs)
        [popoverController presentPopoverFromRect:CGRectMake(point.x, point.y, size.width, size.height)
                                                                        
inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        
        
        
}

Add a button on your main view controller to call the IBAction.
That covers it! One of the new features in iPhoneOS3.2 for iPad. See the screenshots for how it should look, code is downloadable below.

April 13 2010

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

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)

April 12 2010

iPhoneOS SDK – Custom UISlider Graphics

  1. Create a new view based application

Screenshot2010-04-12at15.16.01.BWLVS6GSBm0y.jpg

  1. Add the IBOutlets for the UISliders

In the .h file add:

@interface deCustomSliderViewController : UIViewController {
        
        IBOutlet UISlider *slider1;
        IBOutlet UISlider *slider2;

}

  1. 3. Setup the Interface.

Add a couple sliders to deCustomSliderViewController.xib

Screenshot2010-04-12at15.16.28.sp1lJ5YWNXvi.jpg

And then add the IBOutlet Link – You will only need to do one of these.

Screenshot2010-04-12at15.21.24.3QsjTLPg20UI.jpg

  1. Now its time to make them pretty!

Add your image resources to the project resources folder. You will need one for the bar and one for the knob (the slider bit you touch). I have attached some at the end of this post.

I am using these (credit http://www.mynameise.com/renn and http://365psd.com/day/27/) :

slider-bg.dc4VNOeb5oj2.jpg
slider-knob.Q7fZFMmAxbX4.jpg

  1. Add the UI Code

The final step is just linking the resources to the IBOutlets. Add the following code in your viewDidLoad or viewWillLoad

        //Slider Images
        UIImage *stetchLeftTrack = [[UIImage imageNamed:@"slider-bg.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
        UIImage *stetchRightTrack = [[UIImage imageNamed:@"slider-bg.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
        
        
        //Slider: Top
        slider1.backgroundColor = [UIColor clearColor];        
        [slider1 setThumbImage: [UIImage imageNamed:@"slider-knob.png"] forState:UIControlStateNormal];
        [slider1 setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
        [slider1 setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
        slider1.minimumValue = 0.0;
        slider1.maximumValue = 100.0;
        slider1.continuous = YES;
        slider1.value = 20.0;
        
        //Slider: Middle
        slider2.backgroundColor = [UIColor clearColor];        
        [slider2 setThumbImage: [UIImage imageNamed:@"slider-knob.png"] forState:UIControlStateNormal];
        [slider2 setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
        [slider2 setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
        slider2.minimumValue = 0.0;
        slider2.maximumValue = 100.0;
        slider2.continuous = YES;
        slider2.value = 50.0;

Thats it! It wasn’t too hard at all hey!

Run your app and checkout your new sliders. Mine Looks like this:
Screenshot2010-04-12at15.32.32.VwGIIsHQSwar.jpg

Download Images

Download Project Github

iPhone OS SDK – Single time showing popup for users

It may sometimes be useful to show a one time reminder to your user in your application. This might be asking for a iTunes review, additions to social networks or any other task that It may be rude to ask more than once.

That is exactly what I have put into my application SavingsGoal, with a single time popup in the about screen. This is shown in detail in the example below:

First in viewDidLoad(), I have a reference to the firstViewSocialPopup class.

- (void)viewDidLoad {
[
super 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”;
        
        [
self firstViewSocialPopup];
}

in my .h header file, I have of course added:

-(void)firstViewSocialPopup;

Back in the .m file class I have the method firstViewSocialPopup, which is just checking a NSUserDefaults setting and displaying a UIAlert.

-(void)firstViewSocialPopup{
        NSString *socialPopup = [NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@”toggle_social”]];
        NSLog(@”Social Reminder Status: %@”,socialPopup);
        
        if ([socialPopup isEqualToString: @"YES"]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Social Networking” message:@”Would you help the development team by adding them on Social Networks?” delegate:self cancelButtonTitle:@”No Thanks” otherButtonTitles:@”Twitter”,@”Facebook”,nil];
                [alert show];
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setObject:@"NO" forKey:@"toggle_social"];
        }
        
}

THe UIAlert has delegate self and so sends the button pressed to the UIAlertView delegate (which is its self). This will call the class: (void)alertView: (UIAlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex

And so, in the same class (.m file) I have the following method:

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

                //Custom Open Twitter Page Code
                deHelpers *dehelper = [[deHelpers alloc] init];
                [dehelper openTwitterAppForFollowingUser:@“de_applications"];
                
        } else if (buttonIndex==2) {
                NSLog(@“Open Facebook”);
                
                //Custom Open Twitter Page Code
                url = [NSURL URLWithString:@“http://www.facebook.com/apps/application.php?id=107880612574963"];
                
                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];
                
        }
        
}

Hopefully, you can see the idea, its quite simple. I have included some extra parts in the code for those who are interested exactly how I implement the popup actions. Its using a previously discussed control: PWWebViewController and some DrTouch code: openTwitterAppForFollowingUser.


social.hRbsv9NjXBdY.jpg

April 11 2010

IPhone OS SDK – Use a Zombie to get a better errors about memory allocation

Just a quick note, theres lots of information about NSZombie (NSZombieEnabled), heres the way to enable them:

1. Project -> Edit Active Executable
Screenshot2010-04-11at13.46.39.Qrxcr6fUafop.jpg

2. Goto the Arguments Tab
Screenshot2010-04-11at13.50.31.LmqbaOs3Zmrh.jpg

Screenshot2010-04-11at13.50.34.zbnOfZ81E3Ob.jpg

  1. Set the Variable NSZombieEnabled and set it to YES (note: its Zombie, not Zombies!)

I’ll leave it as an exercise to find out more about NSZombie, its great for memory debugging.

April 09 2010

iPhone OS SDK – Insert a random Number

Generating a random number is a simple task in Objective-C.

all you really need to do is:
int random = random();

Then you can use the integer as you normally would.

But wait..is it possible that I keep getting the same random numbers?

Try the following code in an empty Xcode Project:

        int generated;
        
        for (int i =0; i<10; i++) {
                generated = abs(100000*(random()));
                NSLog(@”New Random Key: %d”,generated);
        }

This gives the output of:
Screenshot2010-04-02at14.14.58.j18TEMlrVoXN.jpg
And yes, they are the same 10 randomly generated numbers! The random number sequence by default is regular and is based off local computer properties. (Note: see how I ran the code twice and I get the same 10 random numbers).

There is one more line that I would say be critical to generating a random number:

        //Real Randomness
        srandom(time(NULL));

Put this before the use of random().

This now sets a new starting point for the random number generator and gives output like one would expect.

        //Real Randomness
        srandom(time(NULL));
        
        int generated;
        
        for (int i =0; i<10; i++) {
                generated = abs(100000*(random()));
                NSLog(@”New Random Key: %d”,generated);
        }

This gives the output: Screenshot2010-04-02at14.15.38.KqQYLXoKVjJM.jpg

This is the best way to quickly generate a random number in Objective-C.

April 08 2010

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

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], @”"];

April 07 2010

iPhone OS SDK – Searching for an item in an array

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.

April 06 2010

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

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!

April 02 2010

Announcing DesignBrief for iPad

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.

icon-512-nobg.mYreHvw0taww.jpg

March 30 2010

iPhone SDK In App Social Links

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!

.

March 26 2010

iPhone SDK | Run a method from a separate class

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!

March 25 2010

iPhone iPad SDK | Get Device Orientation


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

March 24 2010

iPhone SDK Select Cell in Tableview

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

}

Reposted byMarjorieMontenegro MarjorieMontenegro

March 18 2010

iPhone OS SDK – UIAlert & UIAlert Action on button click

Another quick one today, I’ve been out this morning and want to get going on a new iPhone project with a little norsk inspiration.

Using a UIView 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. See (void)alertView:

- (void)alertView: (UIAlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex
{
        if (buttonIndex==0) {
        NSLog(@”In AlertView Delegate”);
        //[self showActionSheet];
        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.

March 17 2010

iPhone OS SDK – Contact Address Property

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

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!

Schweinderl