ITP 342 Mobile App Dev Web View
Web View 2
WebKit The WebKit provides a set of core classes to display web content in windows, and by default, implements features such as following links clicked by the user. The WebKit greatly simplifies the complicated process of loading webpages that is, asynchronously requesting web content from an HTTP server over the network where the response may arrive incrementally, in random order, or partially due to network errors. The WebKit also simplifies the process of displaying content that can contain various MIME types, and multiple frames each with their own set of scrollbars. 3
WebKit You use the WebKit to display web content in a window of your application. It s as simple as creating a view, placing it in a window, and sending a URL load request message. By default, your WebKit application behaves as you would expect without error. The WebKit conveniently creates and manages all the views needed to handle different MIME types. When the user clicks on a link in a page, the WebKit automatically creates the views needed to display the next page. 4
WebKit However, the WebKit doesn t implement a complete set of web browser features. You can, however, extend the WebKit by implementing custom delegate, view, and model objects. For example, you can implement a delegate to display load status, and the current URL. 5
WebKit The WebKit also offers web content editing. If you enable editing in your WebView, users can edit the web content it displays. You can programmatically control the current selection and control editing behavior using a WebView delegate. You can also modify the Document Object Model directly using an Objective-C API. You can also access JavaScript from Objective-C and vice versa. 6
Why use the WebKit? Some applications might want to display web content on demand but don t necessarily want to parse it or understand its structure to display it. Applications like this may not want to open multiple windows or provide back and forward buttons. The WebKit provides a set of classes to support a variety of web content from the most trivial embedded web content application (with web content displayed in a single window) to a fullfeatured web browser such as Safari. 7
Web Content The WebKit does this by hiding the details of the complex task of loading and displaying web content. The web is based on a client-server architecture, in which clients make asynchronous requests to web servers for page content. During this process any number of problems can occur not only when transmitting these requests and responses over the network but also when displaying the content once it s received by your application. Content may be complex. It can contain multiple frame elements, multiple MIME types, such as images and movies. Some MIME types require browser plug-ins to display them. 8
WebKit By default, the WebKit core classes transparently handle programmatic and client requests. The WebKit creates all the necessary model and view classes used to represent and display the incoming content. When a user clicks a link, the WebKit automatically relinquishes control of the old objects and creates new ones to handle the new page. The WebKit views are designed to handle multiple frames, each with their own scroll bar, and many MIME types. You do not need to implement custom views for your application to display web content in your application. 9
Core WebKit Classes You can display web content in a single window by following a few simple steps. Normally, to embed web content in your application you simply create a WebView object, place it in a window, and send a load request message. However, if you want to do something more complex for example, customize the user interface, use multiple windows, or implement any other browser-like features, such as back and forward buttons you will want to understand better how the WebKit classes work together to load and display web content. 10
Frame Model and View Classes The WebKit loosely follows a model-viewcontroller paradigm some objects represent view-controllers that display web content, and other objects represent models that encapsulate web content. WebView Class Reference is the core view class in the WebKit. WebView objects manage interactions between WebFrameView Class Reference objects and WebFrame Class Reference objects. 11
Web View You use the UIWebView class to embed web content in your application. To do so, you simply create a UIWebView object, attach it to a window, and send it a request to load web content. You can also use this class to move back and forward in the history of webpages, and you can even set some web content properties programmatically. 12
Loading Local Content When loading local content, you can either create the content dynamically or load it from a file and display it using one of the following methods: loaddata: MIMEType: textencodingname: baseurl: loadhtmlstring: baseurl: - (void)viewdidload { [super viewdidload]; NSString *path = [[NSBundle mainbundle] pathforresource:@"hig" oftype:@"pdf"]; if (path){ NSData *pdfdata = [NSData datawithcontentsoffile:path]; [(UIWebView *)self.view loaddata:pdfdata MIMEType:@"application/pdf" textencodingname:@"utf-8" baseurl:nil]; } } 13
Loading Local Content When loading local content, you can either create the content dynamically or load it from a file and display it using one of the following methods: loaddata: MIMEType: textencodingname: baseurl: loadhtmlstring: baseurl: SWIFT // QuotesViewController.swift override func viewdidload() { super.viewdidload() if let path = Bundle.main.path(forResource: "HIG", oftype: "pdf"){ let pdfdata = NSData(contentsOfFile: path, options:.mappedifsafe) (self.view as? UIWebView)?.load(pdfData, mimetype: "application/pdf", textencodingname: "utf-8", baseurl: nil) } } 14
Loading Content from the Network To load content from the network, you create an NSURLRequest object and pass it to the loadrequest: method of your web view. You can do this in the viewdidload or viewdidappear method. NSURL *url = [NSURL URLWithString:@"https://www.apple.com"]; NSURLRequest *request = [NSURLRequest requestwithurl:url]; [self.mywebview loadrequest: request]; 15
Loading Content from the Network To load content from the network, you create an NSURLRequest object and pass it to the loadrequest: method of your web view. You can do this in the viewdidload or viewdidappear method. SWIFT let url = URL(string: "https://www.apple.com")! let request = URLRequest(url: url) self.mywebview.loadrequest(request) 16
App Transport Security App Transport Security (ATS) was introduced and enabled by default since ios 9. It forces an app to connect to web services over an HTTPS connection rather than HTTP, keeping user data secure in transit. To handle this, you can: Update all urls to be https Whitelist http connections with key NSExceptionDomains Ignore all app transport security restrictions with key NSAllowsArbitraryLoads 17
Stop a Load Request If, after initiating a network-based load request, you must release your web view for any reason, you must cancel the pending request before releasing the web view. You can cancel a load request using the web view s stoploading method. A typical place to include this code would be in the viewwilldisappear: method of the owning view controller. To determine if a request is still pending, you can check the value in the web view s loading property. - (void)viewwilldisappear:(bool)animated{ [super viewwilldisappear:animated]; if ([self.mywebview isloading]){ [self.mywebview stoploading]; } } // Disconnect the delegate as the webview is hidden self.mywebview.delegate = nil; 18
Stop a Load Request If, after initiating a network-based load request, you must release your web view for any reason, you must cancel the pending request before releasing the web view. You can cancel a load request using the web view s stoploading method. A typical place to include this code would be in the viewwilldisappear: method of the owning view controller. To determine if a request is still pending, you can check the value in the web view s loading property. SWIFT override func viewwilldisappear(_ animated: Bool) { super.viewwilldisappear(animated) if self.mywebview.isloading{ self.mywebview.stoploading() } } // Disconnect the delegate as the webview is hidden self.mywebview.delegate = nil 19
UIWebView Use the loadrequest: method to begin loading web content, the stoploading method to stop loading, and the loading property to find out if a web view is in the process of loading. If you allow the user to move back and forward through the webpage history, then you can use the goback and goforward methods as actions for buttons. Use the cangoback and cangoforward properties to disable the buttons when the user can t move in a direction. 20
UIWebView By default, a web view automatically converts telephone numbers that appear in web content to Phone links. When a Phone link is tapped, the Phone application launches and dials the number. Set the detectsphonenumbers property to NO to turn off this default behavior. You can also use the scalespagetofit property to programmatically set the scale of web content the first time it is displayed in a web view. Thereafter, the user can change the scale using gestures. 21
UIWebView You should not embed UIWebView or UITableView objects in UIScrollView objects. If you do so, unexpected behavior can result because touch events for the two objects can be mixed up and wrongly handled. https://developer.apple.com/library/ios/docum entation/uikit/reference/uiwebview_class/r eference/reference.html 22
Homework Assignment Create a Detail View Create a class that inherits from UIViewController entitled something like DetailViewController. Create a public property to hold an NSDictionary object for a place. Update the title of the navigationitem to the place name. Drag ViewController to the storyboard. Set the class identity to the new class. Add a WebView to display the web page of the URL. Create an IBOutlet for the WebView. 23
Storyboard Create a Show (e.g. Push) segue from the CollectionViewCell to the DetailViewController. 24
Detail View Controller Call the loadrequest: method for the WebView. Add an ActivityIndicatorView that animates when the website is loading by adhering to the UIWebViewDelegate protocol. This is described in future slides in this deck. 25
Collection View Controller Implement the prepareforsegue:sender: method. Check to make sure the segue.identifier is equal to the string that you entered for the identifier in the storyboard. Get the index of the selected cell by calling the indexpathsforselecteditems method for the instance of the CollectionView (self.collectionview). Create an instance of the DetailViewController and set its place property to the selected place. 26
UIWebViewDelegate Set the delegate property to an object conforming to the UIWebViewDelegate protocol if you want to track the loading of web content. While the web content is loading, let's give feedback to the user. Use an Activity View Indicator. 27
Activity Indicator View On the Storyboard, add an Activity Indicator View to the Detail View Create an IBOutlet for the activity indicator In the Attributes Inspector, make sure Hides When Stopped is checked https://developer.apple.com/library/ios/docum entation/uikit/reference/uiactivityindicatorvie w_class/reference/uiactivityindicatorview.h tml 28
Activity Indicator View In the code that has the IBOutlet to the activity indicator Use the startanimating method to start animating the activity indicator Use the stopanimating method to stop animating But when do we start & stop animating? Use the UIWebViewDelegate methods 29
UIWebViewDelegate In the storyboard, select the Web View In the Connections Inspector, set the delegate to the Detail View Controller Make the DetailViewController class adhere to the UIWebViewDelegate protocol Use the following delegate methods: webviewdidstartload: webviewdidfinishload: webview: didfailloadwitherror: 30
Detail View Implement the webviewdidstartload: method and have it start animating the activity indicator Implement the webviewdidfinishload: method and have it stop animating the activity indicator Implement the webview: didfailloadwitherror: method and have it stop animating the activity indicator 31
Detail View Implement the webviewdidstartload: method and have it start animating the activity indicator Implement the webviewdidfinishload: method and have it stop animating the activity indicator Implement the webview: didfailloadwitherror: method and have it stop animating the activity indicator - (void)webviewdidstartload:(uiwebview *)webview{ [self.activityindicator startanimating]; } - (void)webviewdidfinishload:(uiwebview *)webview{ [self.activityindicator stopanimating]; } - (void)webview:(uiwebview *)webview didfailloadwitherror:(nserror *)error{ [self.activityindicator stopanimating]; } 32
Detail View Implement the webviewdidstartload: method and have it start animating the activity indicator Implement the webviewdidfinishload: method and have it stop animating the activity indicator Implement the webview: didfailloadwitherror: method and have it stop animating the activity indicator SWIFT func webviewdidstartload(_ webview: UIWebView) { self.activityindicator.startanimating() } func webviewdidfinishload(_ webview: UIWebView) { self.activityindicator.stopanimating() } func webview(_ webview: UIWebView, didfailloadwitherror error: Error) { self.activityindicator.stopanimating() } 33
Resources https://developer.apple.com/library/ios/documen tation/uikit/reference/uiwebview_class/index. html https://developer.apple.com/library/ios/documen tation/stringstextfonts/conceptual/textandweb iphoneos/displaywebcontent/displaywebcont ent.html https://developer.apple.com/library/mac/docume ntation/cocoa/conceptual/displaywebcontent/ DisplayWebContent.html#//apple_ref/doc/uid/10 000164i 34