Class: 1. To Create A Webview Using Programmatically

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

1.

To Create a Webview using


programmatically

Parent - UIView

class ViewController: UIViewController, UIWebViewDelegate


{

var webView: UIWebView!


override func viewDidLoad() {
super.viewDidLoad()
webView = UIWebView(frame: UIScreen.main.bounds)
webView.delegate = self
view.addSubview(webView)
if let url = URL(string: "http://google.com") {
let request = URLRequest(url: url)
webView.loadRequest(request)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

1.1 Webview forward and Backward action

Button - @IBAction func backAction(sender: AnyObject) {


if webView.canGoBack {
webView.goBack()
}
}

@IBAction func forwardAction(sender: AnyObject) {


if webView.canGoForward {
webView.goForward()
}
}

@IBAction func refreshAction(sender: AnyObject) {


webView.reload()
}

@IBAction func stopAction(sender: AnyObject) {


webView.stopLoading()
}

Property and
Method Description

canGoBack A Boolean value indicating whether the web view can move backward.
If true, able to move backward; otherwise, false.

goBack() Loads the previous location in the back-forward list.

canGoForward A Boolean value indicating whether the web view can move forward. If true,
able to move forward; otherwise, false.

goForward() Loads the next location in the back-forward list.

reload() Reloads the current page.

stopLoading() Stops the loading of any web content managed by the web view.

1.2 webview loading request

override func viewDidLoad()


{
super.viewDidLoad()
webview.loadrequest(NSURL(url: NSURL(String
: “http//google.com”)!))
}

1.3 Load Html page from file


override func viewDidLoad()
{
super.viewDidLoad()
self.webView.loadRequest(NSURLRequest(URL:
NSBundle.mainBundle().URLForResource("index",
withExtension: "html", subdirectory: "faq")!))
}

1.3 Webview Delegate

UIWebview: Conforming

func webViewDidStartLoad(webView: UIWebView) {


UIApplication.sharedApplication().network
ActivityIndicatorVisible = true
}

func webViewDidFinishLoad(webView: UIWebView)


{
UIApplication.sharedApplication().network
ActivityIndicatorVisible = false

navigationTitle.title =
webView.stringByEvaluatingJavaScriptFromString("d
ocument.title")
}

func webView(webView: UIWebView,


didFailLoadWithError error: NSError?) {
UIApplication.sharedApplication().network
ActivityIndicatorVisible = false
}

Method Description

webViewDidStartLoad Sent after a web view starts loading a frame.

webViewDidFinishLoad Sent after a web view finishes loading a frame.

didFailLoadWithError Sent if a web view failed to load a frame.


2.Necessary Function For tableview

func numberOfSections(in tableView: UITableView) -> Int {


}

func tableView(_ tableView: UITableView,numberOfRowsInSection


section: Int)
-> Int {
}
func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath)
-> UITableViewCell {
}

3.UIApplication

#import <uikit/uikit.h>
main(argc,argv)
{
Nsautorelease *pool = [[Nsautoreleasepool
alloc] init]
Int retVal =
UIApplicationMain(argc,argv,nil,nil)
[pool release]
return retVal
}

Explanation

UiapplicationMain() – 1st,2nd arg passes the


parameters to main function itself
-Third arguments set to nil causes to use
Uiapplication
-Fourth arg set to nil Uiapplication
delegate

UIApplicationdelegate

- UIApplication Decides the


UIApplicationDelegate
- UIApplicationDelegate will do the job for
UIApplication.

4.Webservices

webservices:
A web service is a collection of open
protocols and standards used for exchanging data
between applications or systems.

1.Getting the data

2.Parsing the data

3.Using the data

You will generally get the data from a url. The url is usually
provided by the API you are working with. The url will give
you some data, typically in JSON format and you access
the data using a network request.

First, get the URL that will give you the data (like this
one: http://jsonplaceholder.typicode.com/users/1 from JS
ON Placeholder). Paste that url in the JSON Formatter &
Validator to ensure it is valid JSON data.
Second, you’ll need to change some settings to allow you
to access that url from within your app, or else you will get
an error like this:
App Transport Security has blocked a cleartext HTTP
(http://) resource load since it is insecure. Temporary
exceptions can be configured via your app’s Info.plist file.

Follow these instructions to fix that. (If the error remains


after you’ve followed the instructions, try deleting the app
from the simulator and then Run it again.)
Third, go ahead and use URLSession to create a network
request. There are multiple ways to do this. Below are a 7
examples. Why examples? So you can see that there are
multiple ways to create a network request, and by
reviewing and trying each method, you’ll learn the key
components involved. Go ahead, practice these examples
in your own code. (For quick practice, you can add the
code inside your ViewController class in
you ViewController.swift file, then run the project.)(Also
note, some examples handle errors better than others.)

Example 1:

let urlString = URL(string:


"http://jsonplaceholder.typicode.com/users/
1")
if let url = urlString {
let task =
URLSession.shared.dataTask(with: url) {
(data, response, error) in
if error != nil {
print(error)
} else {
if let usableData = data {
print(usableData)
//JSONSerialization
}
}
}
task.resume()

Example 2 (source):

let urlString =
"http://jsonplaceholder.typicode.com/users/
1"
guard let requestUrl =
URL(string:urlString) else { return }
let request = URLRequest(url:requestUrl)
let task =
URLSession.shared.dataTask(with: request) {
(data, response, error) in
if error == nil,let usableData = data {
print(usableData)
//JSONSerialization
}
}
}
task.resume()

Example 3 (source):

let session = URLSession.shared


let url = URL(string:
"http://masilotti.com")!
let task = session.dataTask(with: url) {
(data, _, _) -> Void in
if let data = data {
let string = String(data: data,
encoding: String.Encoding.utf8)
print(string) //JSONSerialization
}
}
task.resume()

Example 4 (source):

let url = URL(string:


"http://jsonplaceholder.typicode.com/users/
3")
let session = URLSession.shared // or let
session = URLSession(configuration:
URLSessionConfiguration.default)
if let usableUrl = url {
let task = session.dataTask(with:
usableUrl, completionHandler: { (data,
response, error) in
if let data = data {
if let stringData =
String(data: data, encoding:
String.Encoding.utf8) {
print(stringData)
//JSONSerialization
}
}
})
task.resume()
}

Example 5 (source):

let config =
URLSessionConfiguration.default
let session = URLSession(configuration:
config)
let url = URL(string: "YOUR URL STRING")!
let task = session.dataTask(with: url) {
(data, response, error) in
if error != nil {

print(error!.localizedDescription)
} else {
print(data) // JSON Serialization
}
}
task.resume()

Example 6:

let url = URL(string:


"http://jsonplaceholder.typicode.com/users/
2")
if let usableUrl = url {
let request = URLRequest(url:
usableUrl)
let task =
URLSession.shared.dataTask(with: request,
completionHandler: { (data, response,
error) in
if let data = data {
if let stringData =
String(data: data, encoding:
String.Encoding.utf8) {
print(stringData)
//JSONSerialization
}
}
})
task.resume()
}

Example 7 (source):
// This shows how you can specify the
settings/parameters instead of using the
default/shared parameters
let urlToRequest =
"http://www.kaleidosblog.com/tutorial/nsurl
session_tutorial.php"
func dataRequest() {
let url4 = URL(string: urlToRequest)!
let session4 = URLSession.shared
let request = NSMutableURLRequest(url:
url4)
request.httpMethod = "POST"
request.cachePolicy =
NSURLRequest.CachePolicy.reloadIgnoringCach
eData
let paramString = "data=Hello"
request.httpBody =
paramString.data(using:
String.Encoding.utf8)
let task = session4.dataTask(with:
request as URLRequest) { (data, response,
error) in
guard let _: Data = data, let _:
URLResponse = response, error == nil else {
print("*****error")
return
}
let dataString = NSString(data: data!,
encoding: String.Encoding.utf8.rawValue)
print("*****This is the data 4:
\(dataString)") //JSONSerialization
}
task.resume()
}
dataRequest()
(Here is another tutorial on network
requests: NSURLSession in Swift: get and post data. This
tutorial does a nice job of explaining the difference
between dataTaskWithUrl and dataTaskWithRequ
est.)

Summary
A lot of examples, I know, but I hope that as you look at the
examples, you’ll notice the main parts of a network call:

1. Specifying the url to use.


2. Creating a task using URLSession, and passing
the url to the task.
3. Doing something with the data received
4. Running the task.

Now that we have the data, we need to do something with


it. Currently the data isn’t very usable, which brings us to
the need of NSJSONSerializationand steps 2 and 3 in
working with an API. You can read that post here:

Parsing the data, Using the data

You might also like