As you know if WebView is widget to render web content in App.
In iPhone there is a UIWebView class which is used to embed web content in your App.
Steps are
1. Create a project with WebView in Layout
2. Create a WebView reference in ViewController class
3. Create a String variable to store URL
4. Convert this string variable to NSURL
5. Call methods with webView reference
See my example i had added in two way
1. First is direct load as shown in web apps
2. Second is to customise content - means as a string (generally
used to read data from web services)
1 in first approach direct load the output will be as
2. Code is as
import UIKit
class ViewController: UIViewController {
@IBOutlet var webView: UIWebView! //Reference of WebView
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let baseUrl = "http://www.stackoverflow.com"
// String constant
let myurl = NSURL(string: baseUrl)!
// Convert it into NSURL
webView.loadRequest(NSURLRequest(URL: merl))
// load data to webView
}
}
2. Second approach is better to work with string response
a. Output
b. code is as
//
// ViewController.swift
// WebEE
//
// Copyright © 2016 Ravi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let baseUrl = "http://www.stackoverflow.com"
let myurl = NSURL(string: baseUrl)!
let session = NSURLSession.sharedSession().
dataTaskWithURL(myurl)
{ (data, response, error) in
if let getData = data
{
let webData = NSString(data: getData,
encoding: NSUTF8StringEncoding)
dispatch_async(dispatch_get_main_queue(),
{
self.webView.loadHTMLString
(String(webData!), baseURL: nil)
})
}
else
{
print("Errors....")
}
}
session.resume()
}
}
No comments:
Post a Comment