UIWebView giving only a white screen - Xcode 7 - ios

Since the recent update to Xcode 7, I have found that my webView will no longer load, it will only show a white screen.
I have searched for a solution, to no avail.
I have coded the webView connection as follows:
class ViewController: UIViewController {
#IBOutlet weak var webviewInstance: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Connect UIWebView to the ordering page
let url = NSURL (string: "http://www.google.com");
let requestObj = NSURLRequest(URL: url!);
webviewInstance.loadRequest(requestObj);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I would greatly appreciate any help with this.

You have to check the app plist file and add the AppTransportSecurity.
Open your plist file and add this. Search for AppTransportSecurity
<key>NSAppTransportSecurity</key>
<dict>
<!--Include to allow all connections (DANGER)-->
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
If you don't add the ATS in your PLIST your link are ignored/blocked. I hope this can help you

A while back I remember reading a question here on SO saying that not implementing
- webView:shouldStartLoadWithRequest:navigationType:
from UIWebViewDelegate was causing problems.
If that don't solve the issue, you can use the delegate methods to debug your problem

Related

How to change src value in UIWebView?

In a UIWebview I want to change
<iframe src=“//player.vimeo.com/video/164231311?autoplay=1” width=“700" height=“394” frameborder=“0" webkitallowfullscreen=“” mozallowfullscreen=“” allowfullscreen=“”></iframe>
to
<iframe src=“//player.vimeo.com/video/164231311" width=“700” height=“394" frameborder=“0” webkitallowfullscreen=“” mozallowfullscreen=“” allowfullscreen=“”></iframe>
since I want the user to be presented with a play button instead of a pause button since autoplay is not allowed on iOS. It'll be more natural for the user to see a play button directly instead of the pause button as in the image below.
How do I do that in a simple way? I’ve tried some stuff like
webView.stringByEvaluatingJavaScript(from:“document.getElementsByTagName(…)
without success so far.
Here I made rough demo code to solve your issue. Put your logic with that and it will solve your issue.
It was tested and had seems working perfectly.
import UIKit
class ViewController: UIViewController,UIWebViewDelegate {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
webView.loadRequest(URLRequest(url: URL(string: "file:///Users/user/Downloads/index.html")!))
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func webViewDidFinishLoad(_ webView: UIWebView) {
// get your current iframe src value
let iframeSrcValue:String = webView.stringByEvaluatingJavaScript(from: "document.getElementsByTagName('iframe')[0].src")!
// Here is your current value with AutoPlay
print(iframeSrcValue)
//Create new URL without Auto Play
let modifiedSrcValue = "https://www.youtube.com/embed/td8pYyuCIIs"
// Apply it to webview
let evaluate: String = "document.getElementsByTagName('iframe')[0].src='\(modifiedSrcValue)';"
webView.stringByEvaluatingJavaScript(from: evaluate)
}
}

UILabel shows wrong Localized String

I have a problem with localizing a string through the Localizable.stringdict. I did setup different localization for different sizes of a Test string. See Localizable.stringdict:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Test</key>
<dict>
<key>NSStringVariableWidthRuleType</key>
<dict>
<key>20</key>
<string>test</string>
<key>25</key>
<string>test message</string>
<key>50</key>
<string>This is a test message</string>
</dict>
</dict>
</dict>
</plist>
My ViewController looks like the following:
class ViewController: UIViewController {
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let string = NSLocalizedString("Test", comment: "This is a test message") as NSString
let widthFormattedString = string.variantFittingPresentationWidth(50) as String
print(widthFormattedString)
label.text = widthFormattedString
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I would like to assign the localized string to a label. The print in my ViewController is printing "This is a test message", but the view is showing "test message". I don't change the text of the label anywhere else. So I wonder why the wrong message is displayed. Can anyone help?
According to the documentation at writing this answer it states that:
Note
Don't call this method when setting user-visible text for standard UIKit controls, such as UILabel. UIKit provides built-in support for adaptive strings, and automatically selects the string width variant appropriate for the current screen size according to the behavior described below.
which seems to confirm what you experience.
The print out you do yourself is correct because it delivers you the string you requested for the value 50:
The print in my ViewController is printing "This is a test message"
Whereas the UILabel gets a the string by the UIKit standard mechanism and appears as:
but the view is showing "test message"
I conclude that you don't need to do it yourself if you use UIKit controls. This is probably helpful for custom controls or other use cases I'm not aware of.

Xcode refresh webView every time the tab is selected

I have the following code for a view which is one of the options attached to a tab on a Tab Bar Controller (swift 3):
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let str8REDURL = URL(string: "https://str8red.com/leaderboard/")
let str8REDURLRequest = URLRequest(url: str8REDURL!)
webView.loadRequest(str8REDURLRequest)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is working perfectly. However, the user can currently have a browse of the site and then select another tab. When they select this tab I would like the webView to reload the URL as above, so basically resetting that view as if it had just loaded. I am assuming there is some "reload" option but can't seem to work it out and would appreciate any guidance.
UPDATE
After a few suggestions I even tried the following with no joy:
func viewWillAppear() {
let str8REDURL = URL(string: "https://str8red.com/leaderboard/")
let str8REDURLRequest = URLRequest(url: str8REDURL!)
webView.loadRequest(str8REDURLRequest)
}
Many thanks, Alan.
Just put the load request in viewWillAppear(), it will be called everytime you change the tab back to that screen
webview.loadRequest() will load the webview content. webview.reload() reloads the last request which has finished loading. Therefore for your case, you can use webview.reload()

UIWebView Produces Blank White Screen

I am having trouble resolving an odd issue with my webView. I am attempting to load a web page (any web page) in a webView which is the sole object within a UIViewController. When I create an instance of the view controller and push it onto the stack, the screen is blank and white. For now I am attempting to load www.apple.com. Here is the relevant code:
UIViewController:
import UIKit
class GoodReadsVC: UIViewController {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL (string: "http://www.apple.com")
let requestObj = NSURLRequest(URL: url!)
webView?.loadRequest(requestObj);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
For what it is worth, I know that the webView is indeed connected to the xib, due to the little dot being filled in the left margin.
Pushing the controller onto the nav stack:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let bookWebView = GoodReadsVC(nibName: "GoodReadsVC", bundle: NSBundle.mainBundle())
self.navigationController!.pushViewController(bookWebView, animated: true)
tableView.reloadData()
}
What am I doing wrong?
This was a case of the loading being blocked by this error:
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.
The solution to this problem may be found here:
Transport security has blocked a cleartext HTTP

UIWebView webViewDidLoadFinish method not called

I've been playing around with web views in swift this evening, but have run into a bit of an issue.
For some reason I'm not able to get the webViewDidStartLoad or webViewDidFinishLoad methods to fire.
In my storyboard, I have an outlet called webView linked to my UIWebView element.
Is anyone able to help me with what I am doing wrong?
This is my viewController.swift file:
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet var webView : UIWebView
var url = NSURL(string: "http://google.com")
override func viewDidLoad() {
super.viewDidLoad()
//load initial URL
var req = NSURLRequest(URL : url)
webView.loadRequest(req)
}
func webViewDidStartLoad(webView : UIWebView) {
//UIApplication.sharedApplication().networkActivityIndicatorVisible = true
println("AA")
}
func webViewDidFinishLoad(webView : UIWebView) {
//UIApplication.sharedApplication().networkActivityIndicatorVisible = false
println("BB")
}
}
Try this!
var req = NSURLRequest(URL: url)
webView.delegate = self
webView.loadRequest(req)
I experienced the same issue, even I did confirmed the UIWebViewDelete to self and implemented its methods.
//Document file url
var docUrl = NSURL(string: "https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwjjwPSnoKfNAhXFRo8KHf6ACGYQFggbMAA&url=http%3A%2F%2Fwww.snee.com%2Fxml%2Fxslt%2Fsample.doc&usg=AFQjCNGG4FxPqcT8RXiIRHcLTu0yYDErdQ&sig2=ejeAlBgIZG5B6W-tS1VrQA&bvm=bv.124272578,d.c2I&cad=rja")
let req = NSURLRequest(URL: docUrl!)
webView.delegate = self
//here is the sole part
webView.scalesPageToFit = true
webView.contentMode = .ScaleAspectFit
webView.loadRequest(req)
above logic worked perfectly with test URl I got from quick google search.
But I when I replaced with mine. webViewDidFinishLoad never get called.
then How we solved?
On backed side we had to define content-type as document in headers. and it works like charm.
So please make sure on your server back-end side as well.
Here's my 2 cents battling with the same problem in SWIFT 3:
class HintViewController: UIViewController, UIWebViewDelegate
Declare the delegate methods this way (note the declaration of the arguments):
func webViewDidStartLoad(_ webView: UIWebView)
func webViewDidFinishLoad(_ webView: UIWebView)
Remember to set self to the webview's delegate property either in Interface Builder (Select the webview, drag from the delegate outlet to the webview from the Connections Inspector OR programmatically: self.webview.delegate = self)
As others noted, setting the delegate of UIWebView and conforming to the UIWebViewDelegate protocol is the best possible solution out there.
For other's who might make it here. I had put my delegate methods in a private extension which couldn't be accessed by the delegate caller. Once I changed the extension to internal the delegates started to get called properly.
There is my detailed solution for Swift 3:
1) in class declaration write the UIWebViewDelegate. For example:
class MyViewController: UIViewController, UIWebViewDelegate {
2) of course in storyboard make link to your UIViewController like this:
#IBOutlet weak var webView: UIWebView!
3) in the func viewDidLoad add one line:
self.webView.delegate = self
Nothing more. Special thinks to LinusGeffarth and LLIAJLbHOu for idea.

Resources