HTML load in UIWebView Crashes - ios

I am trying to load html inside a UIWebView. The html content is loading successfully but the content of html is not responsive in the UIWebView and when I tap the play button in video content, QuickPlayer shows video content but when I try repeat this action my application crashes with this error:
WebThread (16): EXC_BAD_ACCESS (code=2, address=0x115966d50)
Where is my problem in load content?
This is my code for load html:
override func viewDidLoad() {
super.viewDidLoad()
webView.frame = view.bounds
script = "<html><div id=154359904185542><script type=text/JavaScript src=https://www.aparat.com/embed/15stT?data[rnddiv]=154359904185542&data[responsive]=yes></script></div></html>"
webView.delegate = self
OperationQueue.main.addOperation {
self.webView.loadHTMLString(script, baseURL:nil)
}
}

If you are using WKWebView, use code below:
let wkWebView = WKWebView()
wkWebView.loadHTMLString(""<html><div id=154359904185542><script type=text/JavaScript src=https://www.aparat.com/embed/15stT?data[rnddiv]=154359904185542&data[responsive]=yes></script></div></html>", baseURL: nil)
If you are using UIWebView, use code below:
let webView = UIWebView()
webView.loadHTMLString(""<html><div id=154359904185542><script type=text/JavaScript src=https://www.aparat.com/embed/15stT?data[rnddiv]=154359904185542&data[responsive]=yes></script></div></html>", baseURL: nil)

Related

Sending message to WKWebView throws error

I am using WKWebView to load HTML in the popup of my Safari App Extension. I am trying to send a message to this page using webView.evaluateJavaScript("myFunction()") but it fails with error message EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0).
I thought the page isn't loaded in the webView at first and hence throws this error but that is not the case here. The page loads completely but I get this error for some reason. Here is my code.
#IBOutlet var webView: WKWebView!
func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("myFunction()", completionHandler: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
webView.configuration.userContentController.add(self, name: "popup")
webView.configuration.userContentController.add(self, name: "print")
webView.navigationDelegate = self
view.addSubview(webView!)
self.view = webView
if let url = Bundle.main.url(forResource: "MyPopup", withExtension: "html") {
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
}
}
I tried checking error inside the completionHandler but it doesn't go there. Any Ideas?
I believe you need to use main thread to execute JS in the webView. Try wrapping the call to webView.evaluateJavaScript() in DispatchQueue.main.async { }.

loading webview is always nil after disconnecting from tokbox session

I'm working on a native app that uses a webview for most of the functionality, and it uses tokbox video for native video communication. When I initially load the app, the webview loads fine (its created in interface builder).
When a person goes to the video page, I believe the tokbox API makes the webview nil. Once the video is over, I call session.disconnect() and try to reload my webview, but it keeps saying found nil while trying to unwrap optional.
The code that loads the webview looks like this:
func loadApp() {
let htmlFile = Bundle.main.path(forResource: "index", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
// this was added in hopes of initializing the webview again
if webView == nil {
webView = UIWebView(frame: self.view.bounds)
self.view = webView
}
webView.delegate = self
webView.frame = view.bounds
webView.loadHTMLString(html!, baseURL: nil)
}
it keeps failing at webView.delegate = self and the instance variables show that webView is still nil even after the if condition.
EDIT
the webview was hooked by clicking control and dragging to the UIViewController and it looks like this:
#IBOutlet weak var webView: UIWebView!
the loadApp() function is called in 2 places, first in viewDidLoad() where it works fine, but then after calling session.disconnect(), a tokbox callback delegate method is called:
func sessionDidDisconnect(_ session: OTSession) {
print("The client disconnected from the OpenTok session.")
loadApp()
}
this is the second time/place where loadApp() is called, and where it fails.
I don't think webView should be set to nil when you have it setup as a IBOutlet. Try just having webView be var webView: UIWebView? a variable inside of the class and then instantiate it manually and adjust the constraints and position it accordingly.

UIWebView offline error in Swift

I am loading a webpage into my app using UIWebView and following code:
let url = NSURL (string: "http://www.myurl.com");
let requestObj = NSURLRequest(URL: url!);
myWebView.loadRequest(requestObj);
I would like to hide webView if request failed for any reason, for example because of no access to internet. Is there a way to do it?
Use the provided delegate methods of UIWebView
func webViewDidFinishLoad(webView: UIWebView) {
print("webview did finish load!")
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
print("webview did fail load with error: \(error)")
}
Note: To use this method you need implement UIWebViewDelegate in your ViewController and set it with the webView outlet.
myWebView.delegate = self

Loading a preview of a website in a `UIImageView` (Swift)

I'm attempting to load a preview of a website into a UIImageView. I have the following method that is called when the requested website url is received:
func loadWebsite(item:ShareItem) {
activitySpinner.startAnimating()
imageView.setImageForURL(item.asset!.absoluteString) { (image) in
self.showActionButton(true)
self.activitySpinner.stopAnimating()
self.actionButton.titleLabel?.text = "Open"
}
}
I believe there's an error in my logic in the setImageForURL website, which is what is supposed to load the website into my custom image view class:
class MyCustomImageView:UIImageView, UIWebViewDelegate {
var webview:UIWebView?
var completion:((UIImage?)->Void)?
func setImageForURL(urlString:String, completion:((image:UIImage?)->Void)?) {
self.completion = completion
guard let url = NSURL(string: urlString) else {
self.completion?(nil)
return
}
let request = NSURLRequest(URL: url)
webview = UIWebView(frame: self.bounds)
webview!.delegate = self
webview?.scalesPageToFit = true
webview!.loadRequest(request);
}
Does anyone have some insight into how I'm approaching this incorrectly? All the methods are called correctly and in the right order, but no image is shown in the UIImageView.
You need to add the Webview to the image view at some point. By this I mean, using the addSubview method on the imageView, and all this before calling the loadRequest method on the webview. Your webview needs to have a "physical" frame and exist within a parent view before you can load the content.

UIWebview Does NOT complete Load page with "page NOT found" error when URL does not exist

In my iphone app I've got to load a mobile website to a webview (that contain in a separate viewcontroller). All good and working fine.
I need to exit from webview when reach to specific set of URL's. The problem is some of these url's does not exis and therefore page does not finish load (Even with page not found error message to detect current url. Just hangs)
Would like to know if I have to enable any setting in the webView to allow load pages that does not really exist (With page not found error).
OR
Is this possible to know which URL going to load next in
func webViewDidStartLoad(webView: UIWebView)
override func viewDidLoad()
{
super.viewDidLoad()
myWebview.delegate = self
var returnUrlAppendedPaymmentLink = "www.existing_url.com"
let requestURL = NSURL(string: returnUrlAppendedPaymmentLink)
let request = NSURLRequest(URL: requestURL!)
myWebview.loadRequest(request)
}
func webViewDidFinishLoad(webView: UIWebView)
{
var currentUrl = webView.request?.URL?.absoluteString ?? ""
if (currentUrl == "www.special_url.com")
{
self.navigationController?.popViewControllerAnimated(true)
}
}
To intercept specific URLs, use the shouldStartLoadWithRequest delegate method of UIWebView.
You can check the URL of the request in this method to see if this is your "special" URL, do your handling for this case and return false so the web-view won't load it.

Resources