I am trying to use a WKWebView under iOS 9 and one of the pages happens to have a youtube video in an iframe. The video does not display. The same video works in Safari so doesn't seem to be an iOS issue, I assume I am missing a configuration option in the view. A sample URL is http://www.w3schools.com/html/tryit.asp?filename=tryhtml_youtubeiframe.
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate
{
var webView : WKWebView!
override func viewDidLoad()
{
super.viewDidLoad()
let webviewConfiguration = WKWebViewConfiguration()
webviewConfiguration.allowsInlineMediaPlayback = true
webviewConfiguration.preferences.javaScriptCanOpenWindowsAutomatically = true
webviewConfiguration.allowsAirPlayForMediaPlayback = true
webviewConfiguration.allowsPictureInPictureMediaPlayback = true
webviewConfiguration.requiresUserActionForMediaPlayback = false
webView = WKWebView(frame: self.view.bounds,
configuration: webviewConfiguration)
webView.navigationDelegate = self
self.view = webView
let url = NSURL(string: "http://www.w3schools.com/html/tryit.asp?filename=tryhtml_youtubeiframe")
let req = NSURLRequest(URL: url!)
self.webView!.loadRequest(req)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func webView(webView: WKWebView,
didFailNavigation navigation: WKNavigation!,
withError error: NSError)
{
print("didFailNavigation \(error)")
}
func webView(webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: NSError)
{
print("didFailProvisionalNavigation \(error)")
}
}
Go to Projects info.plist file
Added a Key called NSAppTransportSecurity as a Dictionary.
Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES. It works.
Related
I'm currently writing a web view application using WKWebView, which should show a custom error page when there is no internet connection while loading a page. I've tried to handle this by calling a method of WKNavigationDelegate, but it's never called. I'm new to Swift and I already tried some solutions I've found here on stackoverflow, but none of them worked for me. Am I doing something wrong?
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"https://google.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError)
{
let url = Bundle.main.url(forResource: "no_connection", withExtension: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
}
}
The signature func(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { } is incorrect.
Try instead func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { }.
There should be even a warning, telling you that with the first signature you aren't using a delegate function:
I need to add a WKWebview to load web content, inside the content view of UIScrollView.
I'm using the Apple code to load a web page, my outlet viewForWebview is linked correctly, and didFinish is called.
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
#IBOutlet var viewForWebview: UIView!
override func loadView() {
super.loadView()
let myConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: myConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
viewForWebview = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.google.com.au")
let request = URLRequest(url: url!)
webView.load(request)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished navigating to url \(String(describing: webView.url))")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print(error)
}
}
But my the WKWebview is blank:
Just to test, I tried to display the WKWebview directly inside the content view of the scroll view, and it works.
Why is it not working as subview of the content?
Don't override loadView for such actions , you need
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
#IBOutlet var viewForWebview: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let myConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame:.zero, configuration: myConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
viewForWebview.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: viewForWebview.topAnchor),
webView.bottomAnchor.constraint(equalTo: viewForWebview.bottomAnchor),
webView.leadingAnchor.constraint(equalTo: viewForWebview.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: viewForWebview.trailingAnchor)
])
let url = URL(string: "https://www.apple.com")
let request = URLRequest(url: url!)
webView.load(request)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished navigating to url \(String(describing: webView.url))")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print(error)
}
}
My URL
https://app.educationgalaxy.com/games/ipadgame.html?retries=3&name=blastoff&rocket=3&level=2&score=0&gameTimer=150
My Findings
The URL works perfectly with all safari and other browsers.
(including iOS 11 mobile safari)
The URL works with all iOS versions other than iOS 11.
I tried to open the URL on both UIWebView and WKWebView but the same issue happens on both. i.e URL stops loading near completion and
nothing happens then.
Here is what I tried so far
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
// Objects
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
loadUrl()
}
func setupWebView() {
let prefs = WKPreferences()
prefs.javaScriptEnabled = true
let config = WKWebViewConfiguration()
config.preferences = prefs
webView = WKWebView(frame: view.frame, configuration: config)
webView.navigationDelegate = self
view.addSubview(webView)
}
func loadUrl() {
webView.navigationDelegate = self
let url = URL(string: "https://app.educationgalaxy.com/games/ipadgame.html?retries=3&name=blastoff&rocket=3&level=2&score=0&gameTimer=150")!
var request = URLRequest(url: url)
request.cachePolicy = .reloadRevalidatingCacheData
webView.load(request)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print(webView.url!)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print(webView.url!)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("error - \(error)")
}
}
I appreciate your help.
WkWebview is recently introduced and UIWebView is officially deprecated now.
Here is link on same issue posted on Apple forum.And Apple staff is currently figuring out the crash.
enter link description here
https://forums.developer.apple.com/thread/90411
Also try to add WKWebView.framework in your project.
And Transport Security.
Hope this information can help you.
I have analyse your code that is good and you have need check image formate.When I am using bellow code with image url link working fine .
import UIKit
import WebKit
class ViewController: UIViewController ,WKNavigationDelegate {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
loadUrl()
}
func setupWebView() {
let prefs = WKPreferences()
prefs.javaScriptEnabled = true
let config = WKWebViewConfiguration()
config.preferences = prefs
webView = WKWebView(frame: view.frame, configuration: config)
webView.navigationDelegate = self
view.addSubview(webView)
}
func loadUrl() {
webView.navigationDelegate = self
// let url = URL(string: "https://app.educationgalaxy.com/games/ipadgame.html?retries=3&name=blastoff&rocket=3&level=2&score=0&gameTimer=150")!
let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/2/2d/Snake_River_%285mb%29.jpg")!
var request = URLRequest(url: url)
request.cachePolicy = .reloadRevalidatingCacheData
webView.load(request)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print(webView.url!)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print(webView.url!)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("error - \(error)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// Add plist file
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>google.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
if WKWebView don't not support then declare .m file below code:
#import <WebKit/WebKit.h>
#interface WebScannerViewController()
{
WKWebView *webView;
}
#end
#implementation WebScannerViewController
- (void)viewDidLoad
{
[super viewDidLoad];
webView.hidden=YES;
webView.UIDelegate = self;
webView.navigationDelegate = self;
self.loadingSign.hidden = NO;
webView.frame=CGRectMake(0, 94, Width, Height-128);
webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
webView.customUserAgent = #"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17";
webView.navigationDelegate = self;
NSURL *url = [NSURL URLWithString:#"https://app.educationgalaxy.com/games/ipadgame.html?retries=3&name=blastoff&rocket=3&level=2&score=0&gameTimer=150"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
}
i try to get a function called after my Content inside WKWebView is fully loaded. I found the "didFinishNavigation" function at the Apple Swift WKNavigation Documentation.
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
println("WebView content loaded.")
}
But the function never get called.
import UIKit
import WebKit
class ViewController: UIViewController WKNavigationDelegate {
override func loadView() {
super.loadView()
self.webView = WKWebView(frame:self.containerView.frame, configuration: WKWebViewConfiguration())
self.containerView.addSubview(webView!)
self.containerView.clipsToBounds = true
}
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string:"http://google.com/")
var req = NSURLRequest(URL:url)
self.webView!.loadRequest(req)
}
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
println("WebView content loaded.")
}
}
You are not setting the navigationDelegate. Set it and it should be fine.
class ViewController: UIViewController, WKNavigationDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let noLayoutFormatOptions = NSLayoutFormatOptions(rawValue: 0)
let webView = WKWebView(frame: CGRectZero, configuration: WKWebViewConfiguration())
webView.setTranslatesAutoresizingMaskIntoConstraints(false)
webView.navigationDelegate = self
view.addSubview(webView)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: noLayoutFormatOptions, metrics: nil, views: ["webView": webView]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: noLayoutFormatOptions, metrics: nil, views: ["webView": webView]))
let url = NSURL(string: "http://google.com")
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
print("Finished navigating to url \(webView.url)");
}
}
And here is a bit better version with Swift 3.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let configuration = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero, configuration: configuration)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.navigationDelegate = self
view.addSubview(webView)
[webView.topAnchor.constraint(equalTo: view.topAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
webView.leftAnchor.constraint(equalTo: view.leftAnchor),
webView.rightAnchor.constraint(equalTo: view.rightAnchor)].forEach { anchor in
anchor.isActive = true
}
if let url = URL(string: "https://google.com/search?q=westworld") {
webView.load(URLRequest(url: url))
}
}
}
extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished navigating to url \(webView.url)")
}
}
I made a simple mistake for not adding a subview to my View
view.addSubview(webView)
I have created a webView programmatically, here is the complete code
1.. import WebKit
2.. func viewDidLoad()
let request = URLRequest(url: url)
let webView = WKWebView(frame: view.frame)
view.addSubview(webView)
webView.navigationDelegate = self
webView.load(request)
3.. Implement extension for delegate methods
// MARK: WKWebView
extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Start Request")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("Failed Request")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished Request")
}
If we load a webpage, we can forward it to safari, but this causes users to leave our app. Is there any way so that a user visits any webpage and then come back to our application.
If you want some browser type functionality for devices earlier then iOS7, you can use this inline browser
iOS 9 Update:
Apple has introduced a visible standard interface for browsing the web i.e. SFSafariViewController for iOS 9+ devices.
Example:
func showTutorial() {
if let url = URL(string: "https://www.example.com") {
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = true
let vc = SFSafariViewController(url: url, configuration: config)
present(vc, animated: true)
}
}
You can use a UIWebView to display the page in your application.
I wanted to add a more detailed answer for others in the future (key coding!) :
In the object library, search for WebKit View and add it to your ViewController
Place "import WebKit" under "import UIKit"
Create an outlet from the WebKit View you placed in your ViewController in your code directly under the opening "{"
Under "superViewDidLoad()", all you need is this:
let url = URL(string: "your_url_here"")
and
webview.load(URLRequest(url:url!))
and dassit!
I'll attach a copy of my code just in case I didn't explain it very well:
import UIKit
import WebKit
class WebsiteViewController: UIViewController {
#IBOutlet weak var webview: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.eventbrite.com/e/pretty-in-petals-tea-party-tickets-43361370025")
webview.load(URLRequest(url: url!))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Use a UIWebView Here's how to program one. Let me know if you need more help or examples
#user1706456 UIWebView is deprecated by Apple, You can use WKWebView for it.
Here's code to do that :
step1: Import WebKit
Step2:
//ViewController's LifeCycle.
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
}
Step3 :
In ViewDidLoad:
let myURL = URL(string: "www.google.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
Step 4: WKWebView Delegate Methods to handle navigation and loading etc.
//MARK: - WKNavigationDelegate
extension GPWebViewController : WKNavigationDelegate {
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// Refreshing the content in case of editing...
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
}
}