TwitterCounter for @bigclick_dean

dBlog.com.au

My Development Blog

Posts Tagged ‘ NSURL ’

Well I have been asked this a few times and I can see how it would be a very helpful addition to the UIWebView’s feature set. What I am talking about is adding the ability to intercept the event generated when a user selects a link in a webpage being displayed with a UIWebView, this will then allow you to perform any action that you want.

When would you use this I hear you say? Well one person asked me if I knew how to append the users current location onto all HTTP requests? and another just wanted to know how to perform custom actions from an embedded UIWebView.

Once again I will be extending the “Build your very own Web Browser!”, if you haven’t already completed it then I suggest that you head over there now and spend 5 minutes reading it and then downloading the project files at the end.

Start by opening up the WebBrowserTutorialAppDelegate.h file and editing the @interface line to read:

@interface WebBrowserTutorialAppDelegate : NSObject <UIWebViewDelegate> {

What we have done is to make the main AppDelegate a delegate for the UIWebView as well.

Now we need to set our webView to have the main AppDelegate as its delegate, you can do this by opening up WebBrowserTutorialAppDelegate.m and putting the following line just inside the applicationDidFinishLaunching function:

webView.delegate = self;

That is all pretty self explanatory, it just sets the delegate of our webView to self, which in this case is our main application delegate.

Now we are pretty much done, we just need to add the function to catch the link clicks. To do this we need to add a new function, copy the content below to the WebBrowserTutorialAppDelegate.m file:

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
	NSURL *url = request.URL;
	NSString *urlString = url.absoluteString;
	NSLog(urlString);
	return YES;
}

This function will catch all requests and allow you to either manipulate them and pass them on or to perform your own custom action and stop the event from bubbling.

The first line gets the URL of the request, this is the contents inside the href attribute in the anchor tag.
The next line converts the URL to a string so we can log it out. You can access many parts of the NSURL, here are some of them and brief description of what they do.

* absoluteString – An absolute string for the URL. Creating by resolving the receiver’s string against its base.
* absoluteURL – An absolute URL that refers to the same resource as the receiver. If the receiver is already absolute, returns self.
* baseURL – The base URL of the receiver. If the receiver is an absolute URL, returns nil.
* host – The host of the URL.
* parameterString – The parameter string of the URL.
* password – The password of the URL (i.e. http://user:pass@www.test.com would return pass)
* path – Returns the path of a URL.
* port – The port number of the URL.
* query – The query string of the URL.
* relativePath – The relative path of the URL without resolving against the base URL. If the receiver is an absolute URL, this method returns the same value as path.
* relativeString – string representation of the relative portion of the URL. If the receiver is an absolute URL this method returns the same value as absoluteString.
* scheme – The resource specifier of the URL (i.e. http, https, file, ftp, etc).
* user – The user portion of the URL.

Then the third line simply logs the URL to the console, so you will new to open up the console while you run this in the simulator to see the results.

Finally the forth line returns YES, this will allow the UIWebView to follow the link, if you would just like to catch a link and stop the UIWebView from following it then simply return NO.

I hope this will help someone to make a browser with some nice user interaction features.

Thanks,
-Dean

Popularity: 14% [?]

Well while I have been working on the Blog Tutorial I have been learning alot about the iPhone SDK, and once you get into it you will find that it is really quite easy to use. Even the strict data typing!

This tutorial will take you through the process of building your own web browser (well a quick one anyway, with a hard coded URL or hard coded HTML content). When I get a spare minute I will come back and show you how to use the toolbar at the top to add searching, links, etc.

1. Setup Your Project

I am not going to go into the detail of setting up XCode or anything like that in this tutorial as I did it in the RSS Reader Part 1 tutorial, if you don’t know how to set it up then I suggest heading over here and checking it out.

In the top menu click File > New Project and then under the iPhone OS area you will need to choose Window-Based Application.

Window-Based Application Template

Name your project WebBrowserTutorial and click “Save”

2. Adding the UIWebView to the window

In the left hand pane under the Resources folder double click the “MainWindow.xib” . You should see the interface builder fire up and it should look something like below, if you don’t see the inspector window (the third window in the screenshot below) then in the top menu click Tools > Inspector.

Interface Builder Default Screen

Now simply draw the “Web View” component from the library on the right to the window (the second box) and it should automatically resize itself to fit the screen.

Now that the view is on the screen you ned to make some connections, first you will need to hold the control key and click+drag from the Web View to the “File’s Owner” Object in the first screen. You should see the following popup:

iPhone WebView delegate Popup

Just click on the “delegate” Outlet and you are set!

Save and Close the Interface Builder.

3. The Code Behind the Beast (given it is a really small and simple beast)

First off we are going to setup our header file for the UIWebView Outlet.

Open up the “WebBrowserTutorialAppDelegate.h” file from under the Classes folder in the left hand pane, it should look like this

//
//  WebBrowserTutorialAppDelegate.h
//  WebBrowserTutorial
//
//  Created by Dean on 16/09/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface WebBrowserTutorialAppDelegate : NSObject  {
UIWindow *window;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end

We are going to add a UIWebView Outlet just below the “UIWindow *window” line.

The code you need to add is

IBOutlet UIWebView *webView;

What this does is it sets an UIWebView Outlet up and names it “webView” for us to use in the main controller.

Save this file and open up the “WebBrowserTutorialAppDelegate.m” file from the same classes folder.

The initial content should look something like this

//
//  WebBrowserTutorialAppDelegate.m
//  WebBrowserTutorial
//
//  Created by Dean on 16/09/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import "WebBrowserTutorialAppDelegate.h"

@implementation WebBrowserTutorialAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch
[window makeKeyAndVisible];
}

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

@end

We are going to add some code into the applicationDidFinishLaunching method that will be executed, you guessed it, after the application finishes lunching. Don’t you just love Apple’s function names?

Add the following code just below the “applicationDidFinishLaunching” line

// Example 1, loading the content from a URLNSURL
NSURL *url = [NSURL URLWithString:@"http://dblog.com.au"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];

// Example 2, loading the content from a string
//NSString *HTMLData = @"<h1>Hello this is a test</h1>";
//[webView loadHTMLString:HTMLData baseURL:nil];

Most of the code above is pretty easy to understand, I have included two options for you to play with. The first one will load the content from a url (in this case it is http://dblog.com.au) and in the second example it is loading the content from a string, this string can come from anywhere, you could dynamically generate it, it could come from an XML string (like a RSS Feed ;-) ) or pretty much anywhere!

To get the second example to work you will need to comment out the first three lines and uncomment the second two.

You should be ready to save your code and fire your application up.

4. I didn’t see anything! You Suck!

Never fear, I did that on purpose. As you may notice I am trying to press the issue of linking the Outlet to the actual component as if you dont start doing that from the start you will soon get lost and your application development will drive you batty!

You will need to open up the “MainWindow.xib” file in the resources folder again and Control click+drag from the “Web Browser Tutorial App Delegate” Object (see the first image below) to the Webview component in your window. You should see the second window below appear, when it does select the “webView” Outlet.

Web Browser Tutorial App Delegate ObjectUIWebView Outlet

Save and Close the Interface Builder again and try to run your program again, if you used the first example you would see the screen below

dBlog.com.au on your own iPhone Web Browser
[ad]

5. Conclusion

Well that’s it for this tutorial, have a go at playing around with the layout and the different UIWebView loader options and let me know how you go. I will be writing some more articles on the UIWebView in the near future, and hopefully they will help some people get their head around the iPhone Development SDK.

6. Extra Features (added 27/09/2008)

After some requests I have added some extra tips below.
First one is to load a file from the application bundle.
Open up the “WebBrowserTutorialAppDelegate.m” file and edit the applicationDidFinishLaunching function to look like below:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"];
	NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
	[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]]; 

    [window makeKeyAndVisible];
}

What this does is it load the UIWebView content from a local file (in our case “sample.html”).

Now make a new blank file i the resources file called “sample.html” and put the following contents in it:

<html>
<head>
<title>Sample</title>
</head>
<body>
<!-- Load Image from base64 string -->
Image Loaded from base64 string:<br/>
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAALwAA/
+4ADkFkb2JlAGTAAAAAAf/bAIQACQYGBgcGCQcHCQ0JBwkNDwsJCQsPEg4ODw4OEhEODw4ODw4RERQVFxUUERs
bHR0bGycmJiYnLCwsLCwsLCwsLAEKCQkKCwoMCgoMDw0ODQ8TDg4ODhMWDg4QDg4WGxQRERERFBsYGhcXFxoYH
h4bGx4eJiYkJiYsLCwsLCwsLCws/8AAEQgAZABkAwEiAAIRAQMRAf/EAIMAAQACAwEBAAAAAAAAAAAAAAABBQI
EBgcDAQADAQEBAAAAAAAAAAAAAAAAAQMCBAUQAAEEAQMCAwcCBwAAAAAAAAEAAgMEESEFBj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/R7hQZR2/InLO0nwYCMErzPdD9S9KW9C84/iuj4JuIo23iVpLJBjuA6K7zOFKyvZxV
u1Cbxo/R6NtO2QbZTZWhHTV7vFzj1cVuKmv8AKKdSIuZFNYlI+CKNhJJ8Bla3FrfLL09q5vUMdSi8AUqgH+wYO
rnuOvTzUWratQdlbUxWux0XiieKJGyFBOAUJAWpashjTqmlJi1kkVnIZGyVns6kjC4Mcantyn6bc5OhXYWXOsy
9o1GVb7dSZEwHGqtitcnJDvZnAT1994fW/wCnEwPhaR9RupGD/Vhdlw3mm3cpqPfAPpXIMfcVyckA9HsPi1Xr4
YpYnQysEkTwWvY4Agg9QQVS7DwrYdg3Czf2yN8UlodjmFxLGNz3FrAfao2ty2Ojro6aPHhl3PPBXidNPI2KJoy
58hDQPUnC47k/LaMtd9fb5ROToXs1A96c84RvHKLlQ19xbW2+FpEsDg75ycl7Q3QnGmq29u4JtW3UBXJNiTGXS
vGCT7AE6NJy/wAC7edlCWDziGs+aYZGSTr716HxTZIoWCWRoJI0yFpu4/FWt5aPhzouo20BkQA0wFWziuNyHXW
bf1sb7I4xjDQMdNAs1jlTlQO1E+KKPFEDNaeYNB1VHetlxIBW1fs4BAKp4yZJcnXVdFKwpOPsvLhFlt0GSHHqr
uJoAAWhSYA0Kxb0U7vJTrUIzyEWOQpyplZGVD9QmVi46IBsrbsYJzhZVH4wFlZwQV8YHYKtrU59LFs05CzWvE/
IC+wPios6KvBkijwRBo5HcfrZOei+NLPfr1RF17Hnv7HQVe7AW63uwiKFjpoZ6p8SIsGiD3LB/fhETBmja78Fa
sf1O9EVq6EHqWVfvwFtNyiKVi1ND6a49qIiwV/R/9k=" alt="2954488.jpg" /><br/>
<!-- Load Image from URL -->
Image Loaded from URL:<br/>
<img src="http://www.google.com.au/intl/en_au/images/logo.gif"/><br/>
This is the <strong>body</stron> of the text.<br/>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>

This is just a simple html file, but you can also embed images into the html by using their base64 value, check out http://www.abluestar.com/utilities/encode_base64/index.php for info on how to convert images into base64. By using base64 encoded strings you can build a totally self contained file with all images embedded into it.

7. Download the Project Files

I have finally added the source files for this tutorial, download it now!

Popularity: 32% [?]