Subscribe ( RSS )

iPhone Programming Tutorials

Dynamic photo effector
Where To Eat? Find restaurants using GPS.
Intimate Secrets
Got It!
GPS Where To Go? Find Points of Interest using GPS.
Advertise You App Here

iPhone Coding - Learning About UIWebViews by Creating a Web Browser

Wow! It has been a long time since my last tutorial… As I wrote in my last post, I had to take a break due to my wife having our baby.  But, now I’m back and have a great tutorial for you guys.  

Today I will be showing you how to work with a  UIWebview to create a basic web browser.  Here is a screenshot of the app we are going to create.

screenshot_02

Create a View-Based Application

Ok, so let’s get started.  Start by opening up Xcode and click File -> New Project.  Next select View-Based Application and click Choose… Name this project something like iCodeBrowser and click Save.  

screenshot_03

screenshot_04

Now we are ready to begin coding…

Create IBOutlets and IBActions

Before we create the interface for our web browser, we need to establish the IBOutles and Actions to interface with the UI elements in code.  Start by opening up iCodeBrowserViewController.h and add the following code:

screenshot_06

Let’s take a look at this code line by line.  The first thing we added was the <UIWebViewDelegate> to the end of our interface declaration.  This is telling the app that this class will be the delegate for our UIWebview.  

What does it mean to be the delegate you ask? Great question… A delegate is like a handler.  It is responsible for implementing certain methods in order to handle events sent by the object they are the delegate for.  So in our example, we are simply saying that we will implement some of the functionality of the UIWebView.  This is needed so we can capture certain actions of the UIWebView such as a click on a link or so we can tell when a page has started/finished loading.  If it’s still unclear, ask me clarifying questions in the comments section.

Next, we see our 3 lines of declaring IBOutlets.  These are the UI elements that we will be interacting with.  In case you didn’t know, the UIActivityIndicator is the little spinner/loading animation that you see on various apps when content is loading.  We will be using this to show that a page is currently loading.

Following this code, there are 3 IBActions.  IBActions are functions that get called in response to a user interaction with the application (such as tapping a button).  For our basic browser, we are only offering 3 types of functionality.  gotoAddress which will take a user to the address they type in the address bar and goBack/Forward should be pretty self explanatory.  

Creating the User Interface 

Now, let’s create the interface using Interface Builder.  I am going to be showing you how to do this in the video below.

 

Implementing the IBActions

Now that we have our interface, let’s make the app function.  We need to implement our methods.  Open up iCodeBrowserViewController.m and add the following code.

screenshot_01

We need to synthesize our properties to allow us to interact with them.  Synthesizing automatically creates “getter” and “setter” methods for our properties.  Next, let’s implement the viewDidLoad method.  This is where we will be loading our “homepage”.  Add the following code to the viewDidLoad method.

screenshot_08

The viewDidLoad method gets called automatically by our application whenever this view first loads.  We can know for sure that it will get called, so we can put our initialization code here.

The first thing we see is the urlAddress string.  This will be our “homepage”.   You can change this to any address you wish to start with.  Next, we build a URL object with our string.  We need to do this so we can make a web request.  Following this, we build our web request and load it into the webView.  This will display the homepage inside of our webview.  Finally, we set the text of the address bar to the homepage address.  This part is more for aesthetics to let the user know what page they are on.

Next, we implement the method that we connected to the UITextField’s DidEndOnExit method gotoAddress.  Add the following code:

screenshot_09

This is similar to the code we wrote in the viewDidLoad method, except for the fact that we are getting our URL string from the address bar.  This method gets called when the user presses the “Go” button on the keyboard.  The last thing to note here is we call the [addressBar resignFirstResponder] method.  This simply tells the app to hide the keyboard when this method gets called.

The implementation of our Back and Forward methods are pretty easy.  Go ahead and add the following code.

screenshot_10

UIWebViews are pretty cool because of the functionality they offer us built right in to them.  We simply call [webView goBAck] to go back and [webView goForward] to go forward.  This greatly simplifies the interactions with the webview.  If we were to code that functionality from scratch, we would have to create a stack of URLs and continually push and pop them off the stack to keep track of where we need to go.  Thanks Apple for not making us implement this.

Finally, we need to implement the delegate methods for UIWebview.  These methods allow us to write our own code to respond to actions by the UIWebview.  The first methods we will implement are the webViewDidStartLoad and the webViewDidFinishLoad methods.  We will use these to show and hide the activity indicator. Add the following code:

screenshot_11

So when the request is first made for a ULR (before the page starts loading) the webViewDidStartLoad method gets called automatically.  We use this opportunity to start our activity indicator to let the user know the page is loading.  If you don’t have something like this, it simply feels like the app is frozen when in fact, it’s just loading the page.  Finally, the webViewDidFinishLoad method gets called when the page is fully loaded.  After this, we can stop the indicator (and it automatically hides itself).

The very last thing we need to do is define what happens when a user clicks on a link. Add the following method:

screenshot_13

This method gets called automatically whenever the user clicks a link.  This method can be very useful if you want to make a native iPhone application that integrates with a web app.  You can use this method to trap the user’s clicks and have your application respond to web links that get clicked.  In our case, we need it to do 2 things.  The first is to set the text of the address bar to the URL of the link that was clicked on and to load that address into the webview.

One thing to make note of: We do a check to see if the URL scheme is “http”. This is to ensure that the user typed http before their URL.  You can add an else statement here that auto prepends the http if the user did not add it.  This would allow you to type in a url such as “icodeblog.com” rather than having to type “http://www.icodeblog.com”.  I chose to omit it for this tutorial.

Remember, all of this added functionality of a UIWebView can only be gotten if you tell your class that it implements the UIWebViewDelegate protocol as we did in our .h file.

The app should be complete! Click on Build and Go to see this baby in action.  Remember, you must put “http://” in front of your URL’s.  

I hope you have enjoyed this tutorial.  If you have any questions or comments, feel free to leave them in the comments section of this post.  You can download the source here . Happy iCoding!

 

 

iPhone Programming Tutorial - Intro to SOAP Web Services

This tutorial was contributed by Dave (AKA Clarke76) on the Forums.

WebSite: http://viium.com

-Main project on site is eDuo. A .Net app that connects to OWA Exchange and forwards to IMAP account. Free program for those who can’t use Active Sync

 
Important Links:

[WebService] http://viium.com/WebService/HelloWorld.asmx

http://developer.apple.com/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

http://developer.apple.com/documentation/Cocoa/Conceptual/XMLParsing/XMLParsing.html

http://www.w3schools.com/soap/default.asp

 

-After creating our XML data / SOAP  request, we create a URLRequest. We add HTTP Header values, those values you read from the WebService.

-We set the HTTP Method to POST

-We set out HTTP Body to the xml file we created

-We then create our connection, using the request we just setup.

 

 

-Once the connection is setup and delegate is set to self, we need to setup out connection delegate methods.

-The first method just makes sure it can make a connection. If it can, we make sure we have no data in our Data set so we clear it.

-Second method is called when re receive any data. If we do receive data, we just append it to our data set.

-Third Method handles any errors and releases our data and connection if an error occurs.

-Fourth Method: We take the data and create a string for Logging reasons, then release the string.

-We check to make sure an instance of xmlParser does not exist, if it does we release it.

-Create a new instance of xmlParser, set the delegate to self, want to resolve external entities, and start our parsing.

-release our connection and Data

 

 

Now we need to our our delegate methods for NSXMLParser

First method we are check the start of elements. If our element equals “HelloResult” we set our BOOL to true.  Second method records any data between an element if our BOOL is set to true.  Third method checks for our closing element. Once found sets our greeting, releases our MutableString, and set our BOOL back to false.

 

If you have any questions or comments, please leave them in the comments of this post.  You can download the sample code here.

 

iPhone Programming Tutorial - Animating a Ball Using An NSTimer

I have noticed recently many people wanting to create games for the iPhone and are unsure where to start.  A common misconception is that you must use OpenGL ES to create any game with graphics.  I am going to show you today how you can do some simple animation by moving a ball around the screen.  We will not be using OpenGL ES to move the ball.  We will simply be using an NSTimer and a UIImageView.

The code for this could be used in many game applications.  Games such as pong, brick breaker, etc… I will soon do an iPhone game programming tutorial series.  For now, here is a quick tutorial to get you started and excited…

You will need to download this image for this tutorial:

Here are the steps involved in creating this application:

Start With a View-Based Application

We will not need any navigation components for this app.  All we need is a view that we can add a UIImageView to.

Add The Ball Image To Your Project

You can use any image you would like for this.  I used my mad skills in Photoshop to create a shiny red ball for you to use.  This will be the image that we will be “bouncing” around the screen.

Add An IBOutlet For the Ball

This step is necessary as it allows us the link the ball we add to the view in Interface Builder to the code.  This is so we can update the position of the ball at each timestep.

Add The Ball To The View In Interface Builder

All we need to draw the ball on the screen is a UIImageView.  Since we added the ball.png file to our project, it should appear in the drop-down in the attributes section of the UIImageView.  Also, at this step, we need to connect the UIImageView to the ‘ball’ variable by dragging from ‘new referencing outlet’ in the connection inspector of the UIImageView to the ‘File’s Owner’ object.  

Add The Code To Initialize The NSTimer

An NSTimer is very simple to use.  It simple requires that you specify an interval (I used .05) and a function to call at each time-step.  The function we are calling in this tutorial is the onTimer function.  This is a function that we create and will contain the logic to move the ball.

Moving The Ball

This code is all fairly straight forward.  First we add the pos.x and pos.y values (14.0 and 7.0) to the center of the ball object this causes the ball to move diagonally.  Next we simply check to see if the ball has collided with the wall.  If the ball does collide with the wall, we simple reverse the pos.x or the pos.y.

 

That concludes the animation tutorial.  I hope that you go out an make lots of great games after this… Soon, I will start another tutorial series where I we will be creating a full blown game.  If you have any suggestions for games, please leave them in the comments.  Make sure that they are fun but not too in depth, we need to limit the series.  Think in terms of pong, asteroids, etc…

You can download the source code here .  If you have any comments or questions, feel free to leave them in the comments of this post.  You may also post them in the forums. Happy iCoding!

iPhone Programming Tutorial - Using A TabBarView To Switch Between Views

In this tutorial I will show you how to develop a UITabBarController which contains a custom UIView from one of the tabs and a UINavigationController with a UITableView dictated byUISegmentControl in the second tab.

This tutorial was contributed by the user cruffenach.  You can check out his website at http://losectrl-gaincommand.com.

If you would like to contribute a tutorial to iCodeBlog.com, contact me brandon@icodeblog.com

The final product of this tutorial should look something like this:

Setting up the User Interface

The first thing we need to do is open up MainWindow.xib. This will launch interface builder and show what our UITabBarController looks like. In the first tab we see a custom UIView that can be changed however we like, but we are more concerned about the second tab.

Clicking on the TabBarController within the instance window of interface builder and then looking to the Inspector will let us set the type of view controller which each tab will be displaying. The first tab uses a ViewController, and for the second tab we want to use a Navigation Controller type because we will be utilizing the navigation bar to hold our segmented control.

Once in the second tab, we will drag a UISegmentedControl out of our library and onto the navigation bar. The UISegmentedControl will change its look depending on the context you place it in. Here we will essentially be making the TitleView of the NavigationItem a UISegmentedView. This will be important when we get into our code.

With that done, we click on the view of the second tab and set it to be identified as a SegmentedTableViewController or type UITableViewController. We will create that class later in xCode. With that set we drag in a UITableView and connect its DataSource and Delegate methods to our view controller which has now been defined as SegmentedTableViewController. That is all we need to do in interface builder.

Going into xCode we do not need to modify any of the generated classes, however we do need to create a new one. Hit Apple + N and create a new UITableViewController called SegmentedTableViewController. This class will have the datasource methods for a UITableView all ready.

In this class we are going to need an int called selectedSegment, this will be updated to represent which segment is selected. Within the main we need to uncomment the viewDidLoad method and enter the following code.

This code gets the UISegmentedControl from the titleView of the navigationItem, and modifies it to add an action so that when the selected segment changes a method called segmentAction is called. The selectedSegment int is set to the initially selected segment and the titleView is reset with the modified UISegmentedControl.

Next we need to create the method which the UISegmentedControl will call. Here is the code for that method, following the same syntax as a IBAction Method.

This code takes the sender which will be out UISegmentedControl and gets the new selectedSegment from it and sets out variable to that value. Finally it tells the UITableView that something has happened and the data in the table needs to be reloaded.

The final steps is to tell the UITableView that is will be displaying 100 cells and telling the returned cell for each row to have some text which is a product of the selected segment. I chose to have each cell read “I AM CELL (selectedSegment * indexPath.row)”. This essentially means that when segment 0 is selected every cell will read.

I AM CELL 0

When segment 1 is selected the cells will read.

I AM CELL 0

I AM CELL 1

I AM CELL 2

….

When segment 2 is selected the cells will read.

I AM CELL 0

I AM CELL 2

I AM CELL 4

I AM CELL 6

….segment. I chose to

The code to make this happens is…

You can download the source for this tutorial here. icodesegmentcontrol

iPhone Programming Tutorial - Saving/Retrieving Data Using NSUserDefaults

In this tutorial, I will be showing you how you can save and retrieve different types of data using the NSUserDefaults object.  Saving this way is great for when you want to save small amounts of data such as High Scores, Login Information, and program state.

Saving to the NSUserDefaults is great because it does not require any special database knowledge.  So if you don’t want/have an SQLite3 database for your app, this would be the way to go.

In this tutorial, I do the following things:

Start With A View Based Application

This is done so we can start with a blank view.  Since we won’t require any special functionality from our User Interface, this will be perfect.

Set Up IBOutles And An IBAction

We need to set up an IBOutlet for the UILabel and UITextField so that we can interact with the interface in code.  The IBAction (updatePrefs) gets connected to our UIButton that we will add to the Interface. So when the user presses the button, this method will get called and save their data.

Create The Interface In Interface Builder

The interface for this application is pretty simple.  It only requires a UILabel, UIButton, and a UITextField.  Drag each of these components on to your View.

Connect The UI Components To Your Outlets/Action

If you are unfamiliar with what is happening here, read the tutorial Connecting Code To An Interface Builder View. We are simply making the connections between our UIComponents to the code.  This will allow us to interact with them.

Implement The UpdatePrefs Method

This is where the NSUserDefaults actually get saved.  In this method we perform the following tasks:

  • Get reference to the NSUserDefaults object - This is done so we can call methods on it to save our data
  • call the setObject forKey method - This allows us to save a string for a given key.  The key is just a string value that we will use to look up our data.
  • calling the resignFirstResponder method on the UITextField to hide the keyboard when the button (or return) is pressed
  • Update the message text in the label to read “Application Preferences Saved” to notify the user that their preferences have been saved.

Implement The ViewDidLoad Method

We simply start by uncommenting this method.  It gets called after the view loads (all components have been loaded and drawn).  What we want to do in this method is to retrieve the saved NSUserDefault with the key @”greeting”.  This will get the saved name that the user specified.  If this variable is set to nil, then this is the first time the application has been run (or the user never saved their name).

Here are the steps that are taken in this method:

  • Get a Handle to the NSUserDefaults object
  • Retrieve the saved username by calling the getObject method and passing in the key @”greeting”
  • Check if the saved username is nil - If so, display the default welcome message (Welcome guest)
  • If the username is not nil, construct a new string with it using the initWithFormat constructor.  This will allow us to append the username on to the message “Welcome”.  initWithFormat takes 1 or more args.  The first is the format of the string. In our case its @”Welcome %@!”. This is saying replace the “%@” with a string (which is the next parameter).  If you have ever written in C, this is essetially the sprintf method.
  • Once this string is build, we assign it to name.text to update the label

Here is a quick reference for some of the things you can do with NSUserDefaults

Saving

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];

// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];

// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];

// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];

Retrieving

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString
NSString *myString = [prefs stringForKey:@"
keyToLookupString"];

// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"
integerKey"];

// getting an Float
float myFloat = [prefs floatForKey:@"
floatKey"];

If you have any questions or comments, feel free to leave them in the comments section of this post, or post them in the forum. Also be sure and subscribe to the RSS Feed as I will be adding tutorials often.  You can also download the sample code here. Happy iCoding!