swift open website with a webview - swift

My first app with swift... failing terribly.
I'm trying to open a website using webview and found this code online.
class ViewController: UIViewController {
#IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://www.sourcefreeze.com")
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
}
Well I get a fatal error: unexpectedly found nil while unwrapping an Optional value
Why should this value be null ?!

One of two things may be going on.
Your webView is not hooked up to a storyboard element.
Your URL object isn't be initialized
I think it's the former, but I've taken the liberty of making your code safer by optionally binding your NSURL object.
class ViewController: UIViewController {
#IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
if let url = NSURL(string: "http://www.sourcefreeze.com") {
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
}

Change webView.loadRequest(request) to webView?.loadRequest(request).
You need to unblock Transport Security which doesn't allow http loads. Try this.

Related

Check if UIWebView is done loading in Swift

I am making an application that loads a UIWeb View and runs a line of code the moment the webpage is completely loaded.
I am using code like this to load the webpage:
let links = URL (string: "https://example.com")
let loadpage = URLRequest(url: links!)
webPage.loadRequest(load)
How can I run a piece of code the moment the webpage is done? I have tried some examples online but the webpage stops loading while checking if it has loaded?
Thanks!
As stated in the documentation of UIWebView, for apps targeting iOS8 or later you should be using WKWebView instead.
When using a WKWebView, you can make your class conform to WKNavigationDelegate and the delegate method func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) will be called once the webview finishes loading a network request.
If for some reason you are still targeting iOS7 or any previous iOS versions and hence the use of a UIWebView, you can use UIWebViewDelegate's func webViewDidFinishLoad(_ webView: UIWebView) method instead.
Skeleton code for the UIWebView solution:
class WebVC: UIViewController {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
webView.delegate = self
let url = URL(string: "https://example.com")
let request = URLRequest(url: url)
webView.loadRequest(request)
}
}
extension WebVC: UIWebViewDelegate {
func webViewDidFinishLoad(_ webView: UIWebView) {
print("Finished loading")
}
}

Default website when web browser launches xcode swift

I have been creating my own web browser and have successfully done that in xcode. But then I wanted a certain url google for example to load when it first opens, now I have been having issues with this. If anyone can explain to me how to do this it would be great. I have tried multiple things in my ViewController class, but nothing seems to work.
Here's my code snippet, if there's something wrong with it could you tell me? :) thanks
import Cocoa
import WebKit
class ViewController: NSViewController {
#IBOutlet weak var webView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://www.google.com/"
self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: urlString)! as URL))
}
override var representedObject: Any? {
didSet {
}
}
}
The API changed quite a bit in Swift 3. Here is the code that works:
import Cocoa
import WebKit
class ViewController: NSViewController {
#IBOutlet weak var webView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://www.google.com/"
let request = URLRequest(url: URL(string: urlString)!)
self.webView.mainFrame.load(request)
}
}
All the Foundation classes dropped the NS prefix (https://github.com/apple/swift-evolution/blob/master/proposals/0086-drop-foundation-ns.md) and because they changed the way parameters work, the load function changed quite a bit.

"NSURL" is not implicitly convertible to "URL"; did you mean to use "as" to explicitly convert?

I have latest xcode beta, just trying to load a webpage inside an app.
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 url = NSURL (string: "https://www.google.com");
let requestObj = NSURLRequest(URL: url!);
webView.loadRequest(requestObj);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
On this line: let requestObj = NSURLRequest(URL: url!);
I get following error:
"NSURL" is not implicitly convertible to "URL"; did you mean to use "as" to explicitly convert?
I removed the exclamation mark and I get this error:
Cannot convert value of type "NSURL?" to expected argument type "URL"
I've been trying variations on this code from all over the internet for the past four hours. I'm thinking latest swift just doesn't allow this anymore or something, because nothing works. I'm set to a 10.0 Deployment Target and a Xcode 8.0 compatible. But I've also tried earlier versions for both of those settings and I get the same error across all versions of both.
Yes, my webView on the storyboard is properly connected to the ViewController.swift.
In swift 3 you need to use URL instead of NSURL, so create url object like this.
if let url = URL(string: "https://www.google.com") {
webView.load(URLRequest(url: url))
}
Update for Swift 3.1:
let url = URL(string: "https://www.google.com")
let request = URLRequest(url: url!)
webView.load(request)
Notice the use of URL instead of NSURL and load instead of loadRequest.

How do I enable links to open in default browser on WebView [duplicate]

This question already has answers here:
Open WebView URL in Browser
(2 answers)
Closed 7 years ago.
I'm learning OS X/Swift development and have loaded a webpage with contains links to other websites, how I open these links in the default browser. At the moment when clicking on the links nothing happens at all. This is my ViewController.swift contents:
import Cocoa
import WebKit
import Foundation
class ViewController: NSViewController, WebFrameLoadDelegate, WKNavigationDelegate {
#IBOutlet weak var webView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
let URL = "https://test.mywebsite.com"
self.webView.frameLoadDelegate = self
self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: URL)!))
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
I am not entirely clear what you are asking.
I think you are asking how to make links clicked inside a WebView open in the desktop browser (e.g. Safari)?
If this is what you are trying to achieve, you can use the WebPolicyDelegate to determine where a URL should open.
Eg.
import Cocoa
import WebKit
class ViewController: NSViewController, WebFrameLoadDelegate, WebPolicyDelegate {
#IBOutlet weak var webView: WebView!
let defaultURL = "http://www.apple.com/" // note we need the trailing '/' to match with our 'absoluteString' later
override func viewDidLoad() {
super.viewDidLoad()
self.webView.frameLoadDelegate = self
self.webView.policyDelegate = self
self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: defaultURL)!))
}
func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {
if let currentURL = request.URL {
if currentURL.absoluteString == defaultURL {
print("our base/default URL is being called - showing in WebView")
listener.use() // tell the listener to show the request
} else {
print("some other URL - ie. a link has been clicked - ignore in WebView")
listener.ignore() // tell the listener to ignore the request
print("redirecting url: \(currentURL.absoluteString) to standard browser")
NSWorkspace.sharedWorkspace().openURL(currentURL)
}
}
}
}
If this is not what you are asking, could you please edit your question to make it clearer.

Load URL on window load in Swift

I'm trying to load a URL in my WebView in Swift as soon as the main dialog loads. I'm not sure what I'm doing wrong:
class WebViewController: NSViewController {
#IBOutlet var webView: WebView!
// constants
let webUrl = "https://www.google.com"
let webUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36"
override func viewDidLoad() {
super.viewDidLoad()
let request = NSMutableURLRequest(URL: NSURL(string: webUrl)!)
request.setValue(webUA, forHTTPHeaderField: "User-Agent")
webView.mainFrame.loadRequest(request)
}
}
When debugging there are no errors or warnings. I think I linked the nib with the objects properly:
I've been playing around with delegations for a few hours now. The page simply doesn't load.
At first I attempted to use applicationDidFinishLaunching, but that went even worse, because the WebView was never finished being created and was nil.
Alright, so change your ViewController to look like this:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
var urlPath = "http://www.google.com"
func loadAddressUrl() {
let requestUrl = NSURL(string: urlPath)
let request = NSURLRequest(URL: requestUrl!)
webView.loadRequest(request)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadAddressUrl()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
And link the #IBOutlet to your web view controller. Example project available if you want.
Source: https://www.youtube.com/watch?v=Rva9ylPHi2w
Turns out I was pointing to the wrong WebView?!
In the hierarchy, it shows up like this:
I needed to use the one that's highlighted, not the inner one. The inner one was used when I control-dragged from Objects into the physical view object in the layout builder. Somehow dragging to this one fixed it.
Swfit 4 version of loadAddressUrl()
private func loadAddressUrl() {
let requestUrl = NSURL(string: url.text!)
let request = NSURLRequest(url: requestUrl! as URL)
webView.load(request as URLRequest)
}