loading webview is always nil after disconnecting from tokbox session - ios

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.

Related

HTML load in UIWebView Crashes

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)

PDF file not open in UIDocumentInteractionController

I am working on the simulator any there are no apps like adobe to open the pdf files....i am using UIDocumentInteractionController to open the pdf file like below.
let url=URL(fileURLWithPath: "/Users/sai/Library/Developer/CoreSimulator/Devices/425D8615-ADEC-4334-A639-C30B1E675EFA/data/Containers/Data/Application/AB3787BF-F6AC-4111-9847-A0FDC4E899F8/tmp/samplepdf.pdf")
print("--------------------------------- str is \(url)")
if (url != nil) {
// Initialize Document Interaction Controller
self.documentInteractionController = UIDocumentInteractionController(url: url)
// Configure Document Interaction Controller
self.documentInteractionController?.delegate = self
// Preview PDF
self.documentInteractionController?.presentOptionsMenu(from: self.view.frame, in: self.view, animated: true)
}
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
My screen is getting displayed like below
No pdf is being displayed here...is it because there is no app in my simulator which could open pdf files?
Not sure if any Simulator apps will handle pdf documents - maybe News? But you can just add a webView to a view controller and use that to view your pdf.
#IBOutlet weak var webView: UIWebView!
Do the usual safety checks on your url and then:
webView.loadRequest(NSURLRequest(url: url as URL) as URLRequest)
I think there is a path issue.
Replace
let url=URL(fileURLWithPath: "/Users/sai/Library/Developer/CoreSimulator/Devices/425D8615-ADEC-4334-A639-C30B1E675EFA/data/Containers/Data/Application/AB3787BF-F6AC-4111-9847-A0FDC4E899F8/tmp/samplepdf.pdf")
With
let url = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("samplepdf.pdf")
for Swift 3/Xcode 8
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("samplepdf.pdf") as NSURL
Hope that will help.

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.

UIWebView.loading returns false

With swift using the following code:
super.viewDidLoad()
let webView = UIWebView(frame: self.view.bounds)
view.addSubview(webView)
let URL = NSURL(string: "http://www.google.com")
webView.loadRequest(NSURLRequest(URL: URL!))
println(webView.loading)
It prints false and the screen is blank. How is this resolved?
This is perfectly normal behaviour. The UIWebView does not actually start loading content until the UI event, in this case viewDidLoad, has finished executing. So checking it immediately returns false because it has not started just yet.
If you want want to track the success or failure of the UIWebView you should implement the UIWebViewDelegate in your view controller. That way you get callbacks when the request has finished loading or if it has failed.
I'm uncertain exactly on the internals of how UIWebView loads its data or what exactly happens when you call loadRequest, but contrary to my expectations, nothing seems to actually happen until the method which called loadRequest has returned.
Consider the following code:
#IBAction func buttonPress(sender: UIButton) {
let webview = UIWebView(frame: self.view.bounds)
view.addSubview(webview)
let url = NSURL(string: "http://www.google.com")
webview.delegate = self
webview.loadRequest(NSURLRequest(URL: url!))
println("buttonPress: webview.loading? \(webview.loading)")
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
println("webview asking for permission to start loading")
return true
}
func webViewDidStartLoad(webView: UIWebView) {
println("webview did start loading")
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
println("webview did fail load with error: \(error)")
}
func webViewDidFinishLoad(webView: UIWebView) {
println("webview did finish load!")
}
Here, the println in the buttonPress method always executes before any of the other methods. In fact, seemingly no matter what sort of code we put after the loadRequest call, it all executes before the web view even asks shouldStartLoadingWithRequest:.
webview.loadRequest(NSURLRequest(URL: url!))
for _ in 1...10000 {
println("buttonPress: webview.loading? \(webview.loading)")
}
Ten thousand iterations, and yet nothing starts for the webview until after buttonPress method returns.
Meanwhile, webview.loading will only return true between webViewDidStartLoad and one of the two ways the load can stop (failure/success) (webView(webView:didFailLoadWithError:) or webViewDidFinishLoad()).
IF you implement the UIWebViewDelegate protocol and set the web view's delegate, you can implement these methods to keep track of the loading process. If, for whatever reason, your web view isn't loading the URL, implementing webView(webView:didFailLoadWithError:) is the only way to get any sort of diagnostic informatin to determine what failed with the load.

Resources