Thursday, December 30, 2010

Plist Example

-(void)loadFromFile
{
NSMutableDictionary *pData;
NSString *documentsDirectoryPath;
NSString *finalPath;
documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
finalPath = [documentsDirectoryPath stringByAppendingPathComponent:@"gameData.plist"];
pData = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];

switch (m_GameModes)
{
case stretch:
laneDistance = [(NSNumber *)[pData valueForKey:@"stretchDistance"] doubleValue];
qualifyingTime = [(NSNumber *)[pData valueForKey:@"stretchQualifyingTime"] doubleValue];
recordTime = [(NSNumber *)[pData valueForKey:@"stretchRecordTime"] doubleValue];
playerTime = [(NSNumber *)[pData valueForKey:@"stretchPlayerTime"] doubleValue];
break;
case amateur:
laneDistance = [(NSNumber *)[pData valueForKey:@"amateurDistance"] doubleValue];
qualifyingTime = [(NSNumber *)[pData valueForKey:@"amateurQualifyingTime"] doubleValue];
recordTime = [(NSNumber *)[pData valueForKey:@"amateurRecordTime"] doubleValue];
playerTime = [(NSNumber *)[pData valueForKey:@"amateurPlayerTime"] doubleValue];
break;
case professional:
laneDistance = [(NSNumber *)[pData valueForKey:@"professionalDistance"] doubleValue];
qualifyingTime = [(NSNumber *)[pData valueForKey:@"professionalQualifyingTime"] doubleValue];
recordTime = [(NSNumber *)[pData valueForKey:@"professionalRecordTime"] doubleValue];
playerTime = [(NSNumber *)[pData valueForKey:@"professionalPlayerTime"] doubleValue];
break;
case olympiad:
laneDistance = [(NSNumber *)[pData valueForKey:@"olympiadDistance"] doubleValue];
qualifyingTime = [(NSNumber *)[pData valueForKey:@"olympiadQualifyingTime"] doubleValue];
recordTime = [(NSNumber *)[pData valueForKey:@"olympiadRecordTime"] doubleValue];
playerTime = [(NSNumber *)[pData valueForKey:@"olympiadPlayerTime"] doubleValue];
break;
default:
break;
}
}
-(void)saveToFile
{
NSMutableDictionary *pData;
NSString *documentsDirectoryPath;
NSString *finalPath;
documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
finalPath = [documentsDirectoryPath stringByAppendingPathComponent:@"gameData.plist"];
pData = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];

switch (m_GameModes)
{
case stretch:
[pData setValue:[NSNumber numberWithDouble:playerTime] forKey:@"stretchPlayerTime"];
[pData setValue:[NSNumber numberWithDouble:recordTime] forKey:@"stretchRecordTime"];
break;
case amateur:
[pData setValue:[NSNumber numberWithDouble:playerTime] forKey:@"amateurPlayerTime"];
[pData setValue:[NSNumber numberWithDouble:recordTime] forKey:@"amateurRecordTime"];
break;
case professional:
[pData setValue:[NSNumber numberWithDouble:playerTime] forKey:@"professionalPlayerTime"];
[pData setValue:[NSNumber numberWithDouble:recordTime] forKey:@"professionalRecordTime"];
break;
case olympiad:
[pData setValue:[NSNumber numberWithDouble:playerTime] forKey:@"olympiadPlayerTime"];
[pData setValue:[NSNumber numberWithDouble:recordTime] forKey:@"olympiadRecordTime"];
break;
default:
break;
}

[pData writeToFile:finalPath atomically:NO];
}

Using a UIImagePickerController


Apple allows you great access into the images you have taken with your camera or saved on the phone via Safari or such. It also allows you to load up the camera very easily in your code to take pictures from your application.
So the first thing we want to do is start a new project and call it testPicker. You want to create a View based application.
Now that our application is created we want to open up IB and create our view. So double click on thetestPickerViewController.xib file and it will launch IB. The first thing you will notice is that is is a blank view. So lets grab a round rectangle button on the view and also a image view controller. So now our view should look something like this
So now we have to create 2 outlets and an action. The outlets are for the items we placed on the view and the action is for the button click. So make sure you are selecting the File’s Owner name and it should be of type testPickerViewController and create 2 outlets and an action. Name them like the following image.
Now we need to connect them. So you just drag the outlet to the correct item on the view and then grab the action over to the button and a box will popup and select touch up inside as an option. It should look like the following
Now we have to write the new class file. Make sure you are still selected to File’s Owner and go to File -> Write Class Files. You should get the following if you did it the correct spot.
Save the file. It will ask you to merge or overwrite. For this just overwrite the files.
Now that we have our view setup, lets do some code. So the first thing is we must set the UIImagePickerController delegates.
So open up testPickerViewController.h and we want to add in the following to the class reference.
Now we need to add the reference to our image picker so add the following
UIImagePickerController *imgPicker;
Now we need a property for it.
@property (nonatomic, retain) UIImagePickerController *imgPicker;
So the whole file looks something like this now
@interface testPickerViewController : UIViewController   {
    IBOutlet UIButton *button;
    IBOutlet UIImageView *image;
    UIImagePickerController *imgPicker;
}
- (IBAction)grabImage;

@property (nonatomic, retain) UIImagePickerController *imgPicker;

@end
Now save the file and open up testPickerViewController.m. First we need to synthesize the image picker
@synthesize imgPicker;
Now we need to create the viewDidLoad method and init the image picker.
- (void)viewDidLoad {
self.imgPicker = [[UIImagePickerController alloc] init];
self.imgPicker.allowsImageEditing = YES;
self.imgPicker.delegate = self;
self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
There are 3 different types of sources you can use
  • UIImagePickerControllerSourceTypeCamera : to load the camera
  • UIImagePickerControllerSourceTypePhotoLibrary : to load images from library
  • UIImagePickerControllerSourceTypeSavedPhotosAlbum : loads all images saved
Also we set the editing to YES. This will allow your user to crop the image and such. The picker controller’s delegate function we will add later will return the information so you can edit the UIImage that is returned if you really wanted. We will not cover that here. At least not yet.
Now lets load the picker on the button click so make the grabImage method look like this
- (IBAction)grabImage {
[self presentModalViewController:self.imgPicker animated:YES];
}
Now if we click build and go, you will be able to click on the grab images button and your image picker will slide up from the bottom and allow you select a image.
Now we need to add in our delegate methods so we can handle the image when a user selects it. The only one we will really cover is imagePickerController. Here is my complete function to take the selected image and then place it into the imageview we created in IB.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
image.image = img;
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
}
Here is our final product.
As always you can grab the code here.

Thursday, December 23, 2010

UIPicker iPhone SDK - Populated with Year


UIPicker iPhone SDK - Populated with Year

I have a little code I was about to delete, but the snippet is better of it is online somewhere. Its not amazing, but it is searchable!
Objective-C code to create an array of all years since 1960. Perfect for input into a UIPicker


//Get Current Year into i2
NSDateFormatter* formatter = [[[NSDateFormatter allocinit]autorelease];
[formatter setDateFormat:@"yyyy"];
int i2  = [[formatter stringFromDate:[NSDate date]] intValue];


//Create Years Array from 1960 to This year
years = [[NSMutableArray allocinit];
for (int i=1960; i<=i2; i++) {
[years addObject:[NSString stringWithFormat:@"%d",i]];
}


The UIPickerView Delegate Responses



- (NSInteger)numberOfComponentsInPickerView: (UIPickerView*)thePickerView {
return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component
{
return [years count];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView
titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [years objectAtIndex:row];
}

Dont forget the declaration in the interface

//Data
NSMutableArray *years;

UIPickerView (resizing)


UIPickerView (resizing)

One of the prettiest built-in views on the iPhone is theUIPickerView, which presents a slot-machine-like list of options. Unfortunately, this view isn’t particularly easy to use, as its default presentation takes up quite a bit of screen real-estate, and it’s not obvious how to resize it. Today, I’d like to talk about how to tame this view.

Things That Just Ain’t So

When I was Googling for tips on how to control the size ofUIPickerViews, I repeatedly came across the following pieces of advice:
  • Pass in a small CGRect to initWithFrame
  • Make the UIPickerView a subview of another UIView, and then resize the outer view
Neither technique worked for me. (OS 2.2.1)

Affine Transformations

Semi-buried in the UIView class is the astonishingly usefultransform property, which performs arbitrary affine transformations on the view. This lets you do a lot of neat tricks, including scaling theUIPickerView.

Example

Here are the header and implementation files for a PickerDemo class, which is a view controller that manages a view containing aUIPickerView. (I nest the UIPickerView inside another UIView s.t. the PickerDemo controller can be pushed onto a Navigation Controller, with which I was playing when I pulled together this demo.)
#import 

@interface PickerDemo : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {
 UIPickerView* picker;
}

@end
#import "PickerDemo.h"

@implementation PickerDemo

- (void)loadView
{
 picker = [[UIPickerView alloc] initWithFrame:CGRectZero];
 picker.delegate = self;
 picker.dataSource = self;
 picker.showsSelectionIndicator = YES;

 self.view = [[UIView alloc] initWithFrame:CGRectZero];
 [self.view addSubview:picker];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

- (void)dealloc {
    [picker release];
    [super dealloc];
}

#pragma mark UIPickerViewDelegate methods

- (NSString*)pickerView:(UIPickerView*)pv titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
 return [NSString stringWithFormat:@"%d",row];
}

#pragma mark UIPickerViewDataSource methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pv
{
 return 3;
}

- (NSInteger)pickerView:(UIPickerView*)pv numberOfRowsInComponent:(NSInteger)component
{
 return 10;
}

@end
Big reelsThis yields a simple, 3-reel UIPickerView, where each reel contains choices from 0 to 9. No (meaningful) CGRect is given for either theUIPickerView or its enclosing UIView; the former always assumes its default size, while the latter receives its geometry from the (not shown here) Navigation Controller. The result may be seen to the right.

Scaling

Lets try adding a simple scalingCGAffineTransform, by recoding the loadView function as follows:
- (void)loadView
{
 picker = [[UIPickerView alloc] initWithFrame:CGRectZero];
 picker.delegate = self;
 picker.dataSource = self;
 picker.showsSelectionIndicator = YES;
 picker.transform = CGAffineTransformMakeScale(0.5, 0.5);

 self.view = [[UIView alloc] initWithFrame:CGRectZero];
 [self.view addSubview:picker];
}
Big reelsThis nicely scales down the UIPickerView. Unfortunately, the transform is applied to the center of the view, not the upper-left corner, which probably isn’t what one wants. (At least, it’s not what I want.)

Composites

To do a scale relative to the UL corner, we’ll need to execute three transforms:
  • Move the UL corner to the origin
  • Scale relative to the origin
  • Move the origin to the UL corner
We can call these three transformations T0S0, and T1, and since Cocoa/Core Graphics uses row vectors, we will compose them into a single transformation C with this formula:
  • C = T0*S0*T1
A re-written loadView incorporating this transform would look like this:
- (void)loadView
{
 picker = [[UIPickerView alloc] initWithFrame:CGRectZero];
 picker.delegate = self;
 picker.dataSource = self;
 picker.showsSelectionIndicator = YES;

 CGAffineTransform t0 = CGAffineTransformMakeTranslation(picker.bounds.size.width/2, picker.bounds.size.height/2);
 CGAffineTransform s0 = CGAffineTransformMakeScale(0.5, 0.5);
 CGAffineTransform t1 = CGAffineTransformMakeTranslation(-picker.bounds.size.width/2, -picker.bounds.size.height/2);
 picker.transform = CGAffineTransformConcat(t0, CGAffineTransformConcat(s0, t1));

 self.view = [[UIView alloc] initWithFrame:CGRectZero];
 [self.view addSubview:picker];
}
Big reelsThis yields the desired result.

Digression

To be honest, I’m not really happy with the technique I used above to compute the translation offsets; the documentation states that:
The origin of the transform is the value of the center property, or the layer’s anchorPoint property if it was changed. (Use the layer property to get the underlying Core Animation layer object.)
The center property is given in the co-ordinate system of the view’s superview; I’m not familiar with the details of the anchorPointproperty. In the code above, I sort of hand-wave over all of this, and just assume that the origin of the transform will end up in the middle of the bounds rectangle, which is given in the view’s coordinate system. That seems to be true in this case, and might be true in the general case, but it is a hand-wave, and I thought it only fair to point it out.
Reading over that, I’m not sure it clarified anything, but let’s move on.

Brevity

You can compress the transformation composition code quite a bit:
- (void)loadView
{
 picker = [[UIPickerView alloc] initWithFrame:CGRectZero];
 picker.delegate = self;
 picker.dataSource = self;
 picker.showsSelectionIndicator = YES;

 CGFloat dX=picker.bounds.size.width/2, dY=picker.bounds.size.height/2;
 picker.transform = CGAffineTransformTranslate(CGAffineTransformScale(CGAffineTransformMakeTranslation(-dX, -dY), 0.5, 0.5), dX, dY);

 self.view = [[UIView alloc] initWithFrame:CGRectZero];
 [self.view addSubview:picker];
}
Note that the transformations are assembled “backwards” in this idiom; the “innermost” or “first” transformation appears on the “outside” of the expression (its arguments appear last, on the right). Essentially, these functions take an existing transform and prepend a newly defined one to its left.

Friday, December 10, 2010

16 Handy iPhone Apps for Better Blogging


16 Handy iPhone Apps for Better Blogging


The statistics indicate that small businesses with corporate blogs receive 55% more web traffic than small businesses that don’t blog. That’s why it is so important for companies to explore the possibility of adding blogs to their marketing and social strategies.
Blogging isn’t just writing posts. You have to choose images for your posts, monitor your blogging platform and analytics, market your blog and constantly think about new post ideas.
To keep your blogging activities flexible, there are several iPhone apps that you can use. This allows you to keep up with your blog no matter where you are.
These 16 apps will help you do just that. Add your favorite apps for blogging in the comments below.

Blogging Platforms


BlogPress ($2.99) provides complete mobile blogging, including text, images and video. It supports multiple platforms such as BloggerWordPressTypePad and many more.
If you don’t need to have multiple platforms at your disposal, there are some apps for specific blogging platforms available. And many are free.
WordPress for iOS (free) allows you to moderate comments, create or edit posts and add images or videos. You can use this app with both a WordPress.com or self-hosted WordPress.org site.
And if you have a Squarespace site, there’s an iPhone app (free) to create and manage your Squarespace site entirely from your iPhone. It also offers “seamless importing” from WordPress, Blogger, TypePad or Movable Type sites.

Images and Video


Strong images or videos increase reader interest and engagement, so they’re an important part of every blog post. And there are several apps that can help you find, format and insert them on the go.
Photobucket Mobile (free) allows you to upload photos and videos to your blog, Facebook or Twitter. The app also provides access to a searchable media library, with uploading capability and album management.
Adobe Photoshop Express (free) provides one-finger photo editing. You can crop, adjust, filter and add effects or borders on the go.
CellSpin ($1.99) offers the ability to capture video, photo, audio or text and upload it simultaneously on all of your social networking sites like Facebook, Twitter, YouTubeLinkedIn, etc. This could be an easy way to send out photos of the team at a company event to your entire network (at one time!).

Marketing Your Blog


Once you have your blog up and running, you have to start marketing it. Some of the best ways to market your blog are via other social media sites.
Twitter (free) provides you with the same real-time search and trending topics you enjoy on your desktop.
If you are looking for more organization, Tweetdeck (free) provides the ability to create groups, manage multiple accounts as well as sync to your existing desktop Tweetdeck account.
Facebook (free) gives you access to not only your personal Facebook account but any company Pagesto which you’re assigned administrator access, as well. So you can check your Pages and respond to comments.

Analytics


After spending time marketing your blog, it’s only natural to want to see the traffic numbers. Analytics App($6.99) provides complete mobile access to Google Analytics.
Analytics Pro ($6.99) also provides access to Google Analytics, along with features to export data into reports, as well as grouping and sorting of accounts. In addition, it provides an intuitive date picker for setting the date range.
For a quick check on numbers like subscribers, Twitter followers and page views, Ego ($4.99) offers a single dashboard to check the statistics that matter to you.

Idea Gathering


Bloggers are constantly looking for their next post idea. To make sure you don’t forget your best ideas, consider a note-taking app.
Evernote (free) allows you to create text, photo and audio notes that will sync with your PC, Mac or Web. A nice feature is Evernote’s search capability, so you can store and catalog a lot of thoughts without losing them.
If you’re already using Microsoft OneNote, MobileNoter (free) can be used as a standalone app or synced with OneNote. It allows you to create notebooks and share your information. This could be very handy if you have a multi-contributor blog and want to exchange ideas among several people.
As the name implies, SimplenoteSimplenote (free) offers a straightforward, easy note-taking app that syncs with your computer. It’s a great place to jot down a list to reference later.
And while we’re talking about ideas, don’t forget to set up Google ReaderGoogle Reader on your iPhone so you can read your favorite blogs when you’re out of the office. Other blogs are a great source of inspiration.
Writing a blog is hard work. But it doesn’t have to be a burden. Finding a few apps that can make managing your blog a bit easier makes all the difference. What apps are you using to manage your blog? Leave a note in the comments.

Followers