6/22/2009

[iPhone] Saving Simple Data

My hacked (for apps) iPhone & an iPod Touch at...Image by Steve Rhodes via Flickr

This tutorial will show you an easy way of saving simple bits of data so that they can be continue to be used next time the app is started on your iPhone.

Imagine you wanted to save some user settings. In this example I have a UISlider and a UISegmentedControler which I want the user to be able to set, but the iPhone should remember the settings and display them in their last state whenever the iPhone App is restarted.

In the .h file add:
float sliderValue;
float segmentValue; // Use these values to adjust your UI Elements

// You will also need the following methods:
-(NSString *)dataFilePath;
-(void)applicationWillTerminate:(NSNotification *)notification;

In the .m file add:

-(void)viewDidLoad
{
NSString *filePath = [self dataFilePath];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
sliderValue = [[array objectAtIndex:0] floatValue];
segmentValue = [[array objectAtIndex:1] floatValue];
[array release];
}

UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app];
[super viewDidLoad];
}

Above: This is where we load the date if there is any from the last save on the iPhone. First, we check to see if the data file does already exist. If it doesn't, then we don't bother about it. If it does however, we instantiate an array with the contents of the file and add the content to our variable as a float. Remember to save and load them in the same order so you don't mix things up. After having done that, we add some extra code to subscribe to the Notification so that it calls the saving process before quiting the app.
-(NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
}
Above: What this method does is return the full path of the the data file (data.plist). It does that by finding the documents directory on the iPhone/iPod Touch device and appending (adding) "data.plist"

-(void)applicationWillTerminate:(NSNotification *)notification
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject: [NSNumber numberWithFloat:sliderValue]];
[array addObject: [NSNumber numberWithFloat:segmentValue]];
[array writeToFile:[self dataFilePath] atomically: YES];
[array release];
}
Above: The method will be called when, as you might have guessed, the application will get terminated/closed. Here is where you should add all the data you want to keep for the next time the iPhone loads the Application.
Reblog this post [with Zemanta]

6/18/2009

[iPhone] Removing the Keyboard when done.

iphone keyboardImage by _snapp via Flickr

Let me continue with the easy stuff to fill up the Blog a little more.
Today I'll go through how to make the keyboard move out of the way once you are done editing the field.

There are two basic ways of doing it. One, is pressing the DONE key on the keyboard. The other way is tapping with your finger anywhere else on the screen.

Lets clarify:
UITextField *myTextField;
UITextField *myOtherTextField;

-(IBAction)backgroundClick:(id)sender;
-(IBAction)doneEditing:(id)sender;

Using the DONE key:

To make it return with the Done key start by adding the following code:
-(IBAction)doneEditing:(id)sender
{
[sender resignFirstResponder];
}

Any controller can be called to resign the First Responder status. With this simple function done lets set WHEN it will be called.
Open Interface Builder and single click on one of the Text Fields and click ⌘2 to open up the connections inspector.

Connect the Did End on Exit event with the doneEditing function by dragging the little circle symbol next to the event name to the File's Owner.

Repeat this for the other text field to show that you don't need a separate function for every field and try it out.

By tapping it away:

Some keyboard layouts don't have a DONE key. Or even if they have, a lot of people prefere to just tapp it away instead of tapping the small button in the corner. For these situations there is a quick and easy way of solving the problem.

Add the following code:
-(IBAction)backgroundClick:(id)sender
{
[myTextField resignFirstResponder];
[myOtherTextField resignFirstResponder];
}

Can you already guess? Lets see.

Save it again and go back to to Interface Builder.
Drag a Round Rect Button over your view and resize it so that it covers ALL of your view.
Now Select Layout > Send to Back and don't deselect the button anymore. The Button is now behind everything else you are showing.

Press
⌘1 and change the type to Custom.
You now have an invisible button in you back layer. Only thing missing now is to connect the Did touch up inside event to the action backgroundClick and you're done.

Notice that you can ask all of your fields to resign First Responder even if they don't currently have it and it won't cause any problem.
Reblog this post [with Zemanta]

6/17/2009

[iPhone] Saving an Image to the Library from UIImageView

Photo LibraryImage by ahhyeah via Flickr

In my latest app I have a UIImageView which shows an Image that has been taken from the web.
I then wanted to give the user the possibility to save that shown image to his library.
At this point I was getting ready for some longer coding for this but it turned out to be very easy.

To start from the same line let me point out where we are:
I have the following:
UIImageView *imageView;
UIImage *myImage;
-(IBAction)savePicture;


This is how its done:

-(IBAction)savePicture
{
myImage = imageView.image;
/* I assign the image that is being displayed in imageView to myImage */


UIImageWriteToSavedPhotosAlbum
(myImage, self, @selector(image:didFinishSavingWithError:contextInfo:), self);
/* This is the only code needed to save it to the library. See, its easier than you thought. */


[myImage release];
/* Release the image as we don't need to touch that anymore. Always a good thing to release images as early as possible */

}

//This is the error check to make sure we have a nice handling of our saving process.
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
// Lets create an UIAlertView to display that everything is fine.
// That way the user will know it has been actually saved.
NSString *msg = @"Saved!!!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Saved." message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
[str release];
}


And that's it.
If you have any questions, I can try helping you out.
Reblog this post [with Zemanta]

6/16/2009

What's in this Blog? Whom is it for? How often will there be new content?

Hannover Norld-LB BuildingImage by dheuer via Flickr

All very good questions in fact and there are the answers:

What's in this Blog?
I am a Software Engineer working for a middle size Internet Marketing Company. We do web pages, server hosting, custom applications etc and since currently: iPhone Applications which I am currently assigned to.

This summer I will be starting a 3 year schooling program in Software Engineering in a unique system in Germany. I will be part working in the company and part learning at a IT&Media Academy. It's not quiet likeStudying at a University as you earn practical experience just as academic.

So when I'm starting, I will be updating every bit of interesting knowledge on this blog, letting the world take part and learn as much as I am. Be prepared for a lot of info on this page.


Whom is this Blog for?
For anybody interested in Development. Not just for Mobile Applications but for everything that has to do with Software Engineering and Internet Marketing.


How often will there be new updates?
Often. I can't tell you yet exactly how often and I don't want to give you a fix amount as it depends on the course. But be assured that every time I learn something new or old I will be making a post here for you and myself too.
Reblog this post [with Zemanta]