Saturday, 26 April 2014

Coding a Web Browser [Spin a Web]

Select the SUViewController.h file in the project navigator
(see Figure 3-9). The SUViewController.h and SUViewController.m files, together, define the SUViewController class. This is a custom class, which you created—well,technically, it was created on your behalf by the project template, but you can take credit for it. I wont tell anyone. The job of your SUViewController object is to add functionality to, and manage the interactions of, the view objects its connected to. Your app only has one view, so you only needone view controller.


Figure 3-9. Adding properties to SUViewController

Different objects have different roles to play in your app. These roles are explained in Chapter 8. When you add code to your app, you need to decide what class to add it to. This app is very simple; you’ll add all of your customizations to the SUViewController class.
The SUViewController class is a subclass of the UIViewController class, which is defined by the Cocoa Touch framework. This means that your SUViewController class inherits all of the features and behavior of a UIViewController—which is a lot, UIViewController is quite sophisticated.
If you did nothing else, your SUViewController objects would behave exactly like any other
UIViewController object.

The fun is in editing SUViewController.h and SUViewController.m to add new features, or change the behavior it inherited.
Adding Outlets to SUViewController

Start by adding two new properties to SUViewController. A property defines a value associated with an object. In its simplest form, it merely creates a new variable that the object will remember. Add these properties toSUViewController.h:

@property  (weak,nonatomic) IBOutlet  UITextField *urlField;
@property  (weak,nonatomic) IBOutlet  UIWebView  *webView;

When you’re done, your class definition should look like the one in Figure 3-9. So, what does all this mean? Lets examine these declarations in detail:

n     @property is the keyword that tells the Objective-C compiler this is a property declaration.

n     (weak,nonatomic) are optional property attributes. These change certain characteristics of the property. weak means this property does not hang on to the object its connected to (see Chapter 21). nonatomic makes accessing this property more efficient by relaxing certain rules with respect to multi-tasking (see Chapter 24).

n     IBOutlet is a very important keyword that makes this property appear as an outlet in Interface Builder.

n     UITextField*/UIWebView* is the type of the property. In this case, its the class of the object this property stores. The asterisk means this property is a reference to an object, not the object itself. In Objective-C, you can only store references to objects.

n     urlField/webBrowser is the name of the property.

By adding these properties to SUViewController, you enable an SUViewController object to be directly 
connected to one text field object (via its urlField property) and one web view object (via its webBrowser property).

You’ve defined the potential for being connected to two other objects, but you havent connected them.For that, you’ll use Interface Builder.

Connecting Custom Outlets

Click on the Main_iPhone.storyboard file in the project navigator. Find, and select, the View Controller object in the outline or in the dock below the view, both shown in Figure 3-10.


Figure 3-10. Selecting the View Controller object for a scene

In most cases, a screen in iOS starts out as just a single view controller object. When its time for
that view to appear on the screen, the view controller loads its view objects from an Interface Builder file—either a scene in a .storyboard file or from an .xib file. In this app, your SUViewController object will load the 
SUViewControllerscene in the Main_iPhone.storyboard file, creating all the objects and connections therein. Connections between objects and the view controller will be made between the new objects and the existing controller object. 
Once the scene file is loaded, the connected properties of the controller now refer to the objects created by
the Interface Builder file.

You’ve created the objects, and now you’re going to connect them together. Show the connections inspector. In it, you’ll see the urlField and webView properties you just added to SUViewController.h. These appear in Interface Builder because you included the IBOutlet keyword in your @property declaration.

Drag the connection circle to the right of the urlField and connect it to the text field object in the navigation bar, as shown in Figure 3-11. Now, when the SUViewController scene is loaded, the urlField property of yourSUViewController object will refer (point) to the text field object in your interface. Pretty cool, huh?


Figure 3-11. Connecting an owner object outlet


Another handy way of setting connections is to control+drag or right-click+drag from the object with the connection to the object you want it connected to. Holding down the controlkey, click the View Controller object andconnect it to the web view object, as shown in Figure 3-12.


Figure 3-12. Connecting the web view outlet


When you release the mouse button, a pop-up menu will appear asking you to choose which outlet to set. Choose webView.

Adding Actions to SUViewController

So why did you do all of this (creating outlet properties and connecting them in Interface Builder)? Your controller object needs to get the value of the URL typed by the user and communicate that to the web view object, so theweb view knows what URL to load. Your SUViewController is acting as a liaison or manager, getting data from one object (the text field) and assigning tasks to another (the web view). Do you see now why its called a controller?
Its a simple task, but there has to be some code that will make it happen. Select the SUViewController.m file in the project navigator and switch to the assistant editor view, as shown in Figure 3-13.


Figure 3-13. Assistant view of SUViewControler.m and SUViewController.h

The assistant editor view shows both sides of your SUViewController class. On the left is its
@implementation  (in the .m file), and on the right is its @interface (in the .h file). A classs interface describes what an object does. Its implementation defines how it does it.
The code you write to accomplish things goes in the .m (implementation) file, where you give each task a method name. In the .h (interface) file you then declare the names of those methods and properties that other objectsneed to use your object. This is how objects encapsulate, or hide, the details of what they do. This makes them simpler to use, just as a complicated device (like an iPod) hides the details of how it works behind an easy-to-useinterface. The entire iOS is written this way. In fact, the Cocoa Touch software development kit (SDK) is mostly the .h files that Apple wrote to make iOS work. Apple gives you the .h files, so you know how to use any object in iOS, while the .m files—the part with the actual code—stays locked away in Cupertino.

In the SUViewController.m file, you see that two methods (-viewDidLoad and
-didReceiveMemoryWarning) already exist. Between those and the @end statement, add this new method:

-  (IBAction)loadLocation:(id)sender
{
NSString   *urlText = self.urlField.text;

if (![urlText  hasPrefix:@"http:"] &&   ![urlText  hasPrefix:@"https:"])  if  (![urlText hasPrefix:@"//"])



urlText = [@"//" stringByAppendingString:urlText]; urlText = [@"http:" stringByAppendingString:urlText];
}

NSURL  *url = [NSURL  URLWithString:urlText];

[self.webView   loadRequest:[NSURLRequest requestWithURL:url]];
}

This method does one simple task: load the web page at the URL entered by the user. This will require three basic steps:

1.       Get the string of characters the user typed into the text field

2.       Convert that string of characters into an URL object

3.       Request that the web view object load the page at that URL Heres the breakdown of this code.

NSString   *urlText = self.urlField.text;

The first line declares a new string object variable, named urlText, and assigns it the value of the text property of the urlField property of this object. The self keyword refers to this object (SUViewController). The urlField property is the one you just added to this class. Your urlField refers to a UITextField object, and a UITextField object has a text property that contains the characters currently in the field—either ones the user typed or those you put thereprogrammatically. (See, I used the word “programmatically” again.)
Part one of your task is already accomplished; you’ve retrieved the text of the URL using the
urlField property you defined and connected. The next few lines might look a little strange.

if (![urlText  hasPrefix:@"http:"] &&   ![urlText  hasPrefix:@"https:"])  if  (![urlText hasPrefix:@"//"])
urlText = [@"//" stringByAppendingString:urlText]; urlText = [@"http:" stringByAppendingString:urlText];
}

If you’re comfortable with Objective-C, take a close look at this code. It isnt critical to your app; you could leave it out, and your app would still work. It does, however, perform a kindness for your users. It checks to see if thestring the user typed in starts with http:// or https://, the standard protocols for a web page. If these standard URL elements are missing, this code inserts one automatically.

No comments:

Post a Comment