iOS

Create intricately formatted content for you app using UIWebView


At first glance, the UIWebView class may seem like something you'd want to use only when embedding web-based content into your app. However, it turns out that UIWebView is worth considering almost anytime you need to display formatted content. Depending on your needs and skill level, it is often a much simpler alternative to UITextView and CoreText. In this post, we'll look at several ways to use UIWebView to easily display both web pages and formatted text.

New Project

Open Xcode and from the File menu, select New, and then New Project. A new workspace window will appear, and you will be presented with several application templates to choose from.

On the left-hand side, select Application from the iOS section. Select Single View Application and click the Next button. (Figure A)

Figure A

On the next pane, enter WebView for the Product Name and com.myappcompany as the Company Identifier. (Feel free to substitute your own product name and company identifier).

Leave the Class Prefix as is. It should be blank - XYZ is just a placeholder hint.

Make sure only Use Automatic Reference Counting and Use Storyboards are checked.

Set Device Family to iPhone, and click Next. (Figure B)

Figure B

A new pane will appear asking you where you would like to save the project. XCode will create a WebView project folder inside the directory you select.

Once the project is created, Xcode will open a workspace window with your new project.

Creating the User Interface

Click on MainStoryboard.storyboard in the Files and Groups pane. Next, go to the Object Library located on the lower right-hand side of the workspace and drag a UIWebView onto the main view such that it fills the entire screen, leaving only the status bar visible. Then place a UIButton object onto the lower left corner of the UIWebView. Double-click on the button and change its label to "Back". Figure C shows the situation so far.

Figure C

Next, click on the Assistant Editor in the upper right corner of the Xcode Interface. (Figure D)

Figure D

The Assistant Editor will display ViewController.h in an adjacent pane as shown in Figure E. Click on the UIWebView to select it, then press the Control key and drag from the web view to just under the word "@interface" in ViewController.h. When you release your finger from the mouse, the Connection dialog will appear. Type "myWebView" into the Name field and press Enter. You have now created an outlet named myWebView and connected it to the UIWebView in the storyboard.

Figure E

Click on the Standard Editor button to close the Assistant Editor.

Adding the code

Click on ViewController.m in the Files and Groups pane. Modify viewDidLoad: as shown below and add the other four methods underneath it. Be sure to include the comments ('//') as shown in viewDidLoad: We want to run only one of the example methods at a time.

- (void)viewDidLoad
{
[super viewDidLoad];
[self showWebURL];
// [self showString];
// [self showFile];
}
- (void)showWebURL
{
NSURL *url = [[NSURL alloc] initWithString:@"http://m.techrepublic.com/blog/ios-app-builder"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.myWebView loadRequest:request];
}
- (void)showString
{
NSString *htmlString = @"<html><body>";
htmlString = [htmlString stringByAppendingString:@"Hello App Builders! <br /> <br />"];
htmlString = [htmlString stringByAppendingString:@"All <strong>string</strong> things are possible in a UIWebView"];
htmlString = [htmlString stringByAppendingString:@"</body></html>"];
// UIWebView uses baseURL to find style sheets, images, etc that you include in your HTML.
NSURL *bundleUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[self.myWebView loadHTMLString:htmlString baseURL:bundleUrl];
}
- (void)showFile
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mypage" ofType:@"html"] isDirectory:NO];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.myWebView loadRequest:request];
}
- (IBAction)backButtonTapped:(id)sender
{
[self.myWebView goBack];
}

Wiring the Button

Before we run the app, we need to connect the Back button to the backButtonTapped: method. Click on MainStoryboard.storyboard, and then click on the button and Control-drag to the View Controller object. When you release the mouse, a pop-up will appear as shown in Figure F. Click on backButtonTapped: to make the connection.

Figure F

Technique #1 - Showing Web Content

Build and run the app. On our first run, we are calling the showWebURL: method, which displays the iOS App Builder site as shown in Figure G. This is the classic way to use UIWebView - embedding web content into your app. Try clicking on one of the article links to go to another page.

Figure G

As you can see, UIWebView works much like a mini-web browser, except that there are no navigation controls. Fortunately, we've added one of our own. Clicking on the Back button fires the goBack: method on UIWebView, and just as you'd expect, the previous page in the browsing history is retrieved. UIWebView also has a goForward: method to traverse the page history in the forward direction.

Technique #1 - Displaying raw HTML

UIWebView is also capable of accepting string input for display. In the showString: method, we create a simple string of text with HTML tags and pass it to UIWebView for display. To see this in action, modify viewDidLoad: as follows:

- (void)viewDidLoad
{
[super viewDidLoad];
[self showString];
// [self showFile];
}
Build and run the app again. Note in Figure H that the word "string" is in bold font just as we directed with the <strong> tag. UIWebView will even honor external style sheets specified using the HTML <link> tag. While this may seem like a lot of work to display a simple line of text, it can be a very powerful tool when you need to display sizable pre-formatted string of text from a database, for example, a blog post.

Figure H

Technique #1 - Displaying an HTML file

UIWebView can also display local html files. Let's create one now. From the Xcode the File menu, select New, and then File. (Figure I)

Figure I

Select "Other" under the iOS section, click on the Empty template, and then click Next. On the following Save-As screen, name the file "mypage.html" and click on Create. We now have an empty file ready for our HTML. Click on mypage.html and add the following code:

<html>
<style>
body { font-size: 22px; color: red;}
</style>
<body>
All file things are possible in a UIWebView!
</body>
</html>
Go back to ViewController.m and modify viewDidLoad: one last time as shown below, then build and run the app. The results are shown in Figure J.
- (void)viewDidLoad
{
[super viewDidLoad];
[self showFile];
}

UIWebView again honors our styling to change the size and color of the font.

Figure J

Bottom line

Using this file-based technique, you can create intricately formatted content using your favorite HTML editor and then simply drop the files into your project for use by UIWebView. If your HTML references image files or external style sheets, remember to drop files those into your project as well. This is a very easy way to put sharp looking tutorials, documentation, or other content into your apps without getting into the complexities of CoreText.

I encourage you to visit the Apple's Developer site to learn more about UIWebView. There are additional useful methods you will want to learn, including a complete set of delegate methods that let you control UIWebView's behavior in a very fine-grained manner.

Also read:

About

Scott Kantner started his IT career on a Radio Shack TRS-80 model I back in 1978. He is CTO of a hosting/colocation firm, a tech writer, and an avid iOS app developer. He has several music-related apps in the App Store that you can learn about at OnS...

0 comments