I am new to Swift / iOS and am trying to use webView to be able to view a url. Searching this site and countless others I managed to be able to access google by using
var url = NSURL(string: "https://www.google.com")
This works fine with "https" but does not work if I use "http".
Is the "s" a security setting? How can I view sites with a "URL scheme" of "http".
Hope you can assist.
import UIKit
import WebKit
import Foundation
class ViewController: UIViewController {
#IBOutlet var containerView : UIView? = nil
var webView:WKWebView?
//instatiating the webView
override func loadView() {
super.loadView()
self.webView = WKWebView()
self.view = self.webView
}
override func viewDidLoad() {
super.viewDidLoad()
//Loading and showing a web-page
var url = NSURL(string: "https://www.google.com")
//var url = NSURL(string: "http://www.google.com")
var req = NSURLRequest(URL:url!)
self.webView!.loadRequest(req)
}
}
Editing the info.plist and adding App Transport Security Settings and add to that Allow Arbitrary Loads and the Boolean = yes
just add this line in your info.plist
info.plist is an XML file so you can place this code more or less anywhere inside the file.
this is the configuration to allow a specific domain to use HTTP instead of HTTPS:
<key>NSAppTransportSecurity</key>
<dict>
<!--Include to allow all connections (DANGER)-->
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Try with http://stackoverflow.com. it worked for me
var url = NSURL(string: "http://stackoverflow.com/")
//var url = NSURL(string: "http://www.google.com")//Comment this
var req = NSURLRequest(URL:url!)
self.webView!.loadRequest(req)
Related
I'm trying to load local html5 files to Xcode to create an ios App. I tried using a template and it uses both local and web based paths to create a very nice ios app in Xcode.
I need to learn about how to create a a webview app that has normal features and can load my local html5 webapps into Xcode for compiling an ios app.
I tried the following code, and it works alright when loading a url based html5 page.
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
https://developer.apple.com/documentation/webkit/wkwebview
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}}
I need to change the URL to local file path. The above code page from apple documentation suggests that I use load(_: ) to load local html files. I'm not sure how to use this function. So, I tried code samples from alternate sources, and here's some part of the code I'm trying with for the Webview app.
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
#IBOutlet var webView: WKWebView!
//var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
guard let fileUrl = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www-WebsiteContent") else { return; }
//let urlPath = Bundle.main.url(forResource: "input", withExtension: "txt")
if fileUrl != "" {
let url = URL(fileURLWithPath: fileUrl)
//let url = init(_: fileURLWithPath, path: "www-WebsiteContent/index.html")
webView.loadFileURL(url, allowingReadAccessTo : url)
let request = URLRequest(url: url)
webView.load(request)
}
//let myURL = URL(string:"file:///www-WebsiteContent/index.html")
//let myRequest = URLRequest(url: myURL!)
//webView.load(myRequest)
//webView.loadFileURL(URL: , webView.allowingReadAccessTo readAccessURL: URL)
}}
I'm using latest Xcode version on Macbook Air with latest Swift 5 version. There's a main storyboard with the webview object, and a viewcontroller.swift file.
The error is that when I run the project, it doesn't display the index.html file in the www-WebsiteContent folder. Maybe I wasn't able to connect the webview overlay to the viewcontroller.swift file properly.
Things I need to understand:
Can I run the above code and compile it as a complete ios app? Or would I need to edit AppDelegate or SceneDelegate files too? I've only edited the viewcontroller.swift file as a new project.
How can I resize the webview overlay to automatic width and height of the ios device? I have an html5 webapp files that I need to convert to an ios app. How can I create this webview so that it fits all the device types screen sizes? My html5 app fits perfectly when viewed in the device browser.
I am loading a url in a UIWebView as below:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var MainWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://www.odysseynewsmagazine.net")
let request = NSURLRequest(url:url! as URL)
self.MainWebView!.loadRequest(request as URLRequest)
}
}
IBOutlet is connected and my .plist has App Transport Security Settings and Allow Arbitrary Loads set to YES.
Why is the app building a blank page?
Try
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.google.com")! // it works ? Comment line and uncomment the following one
// let url = URL(string: "http://www.odysseynewsmagazine.net")!
let request = URLRequest(url: url)
mainWebView.load(request) // var should start with lower case
}
If it works, change the URL. If it doesn't work only with your URL then there's something wrong with either the site or ATS. Paste the console output.
Ok. So here is the normal web-view loading your URL with just the App transport security setting
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = NSURL(string: "http://www.odysseynewsmagazine.net")
let request = NSURLRequest(url:url! as URL)
self.webView.loadRequest(request as URLRequest)
}
And the plist setting set to
Allow Arbitrary Loads to YES.
And result is:
Your code is just fine!!!
Your issue is you have missed add NSAllowsArbitraryLoadsInWebContent key in your NSAppTransportSecurity dictionary and set value to TRUE
To fix this you only need replicate the below image in your plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
</dict>
Your webView rendering the webView content, your code is unchanged
Hope this helps
Really basic question here: I have a web view in my view controller, and can't figure out how to make it display a website. None of the solutions I've been able to find are working for me. Most of what I've seen online tells me to enter the code below (sample url), but I get errors telling me to delete '#' and add several ';' but doing so does not resolve the issues.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *fullURL = #"http://conecode.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];
I'm not sure why I'm having so much difficulty with something that seems so simple...here is all I have in my code. How do I make the web view show a website? Thanks in advance! I've already learned a lot from this community.
import UIKit
class SecondViewController: UIViewController {
#IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
After a bit more digging here's what I've found that seems to work:
var url = NSURL(string: "https://www.google.com")
var request = NSURLRequest(URL: url!)
webView.loadRequest(request)
I'm not sure how this relates to the earlier code snippets I had been finding, and it doesn't work for http (vs https) websites, so that's something I still need to figure out...
Here is how to load a page to UIWebView.
#IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var url = NSURL(string: "https://www.google.com")
var request = NSURLRequest(URL: url!)
webView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
For the problem with http NSAppTransportSecurity key to your info.plist
Here is example:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>google.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
NSAllowsArbitraryLoads - it allow to connect to any http site.
or you could specifity the site with NSExceptionDomains - like I post in the code above.
On more thing - Check WKWebView - it much better than UIWebView for displaying pages. - https://developer.apple.com/library/ios/documentation/WebKit/Reference/WKWebView_Ref/
I'm new to Swift programming and I'm trying to load the web content of a website into my app using UIWebView. But all I get is the skeleton of the webpage i.e. the html. How should I load the css and javascript of the website?
This is my ViewController.swift file.
//
// ViewController.swift
//
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = NSURL(string: "http://www.smartanalyzers.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!)
{
(data, response, error) in
if error == nil {
var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(urlContent)
dispatch_async(dispatch_get_main_queue()){
self.webView.loadHTMLString(urlContent! as String, baseURL: nil) }
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You can load the website in a much simpler way:
if let url = NSURL(string: "http://www.smartanalyzers.com") {
webView.loadRequest(NSURLRequest(URL: url))
}
However when running this in iOS9 you need to disable Apple's App Transport Security for this website or it will not load, because it does not use HTTPS.
To allow HTTP loads from the website's domain you have to add this to your Info.plist file:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>smartanalyzers.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
If you see that fonts or images are still not loaded correctly, check if they are loaded from different domains and add those domains to the NSExceptionDomains Dictionary in Info.plist
I'm trying to make it work but nothing.
I want to make (URL textfield) on (RightVC) as (webview)-url on (LeftVC).
I saved the textfield with this code:
#IBAction func save(sender: UIButton) {
NSUserDefaults.standardUserDefaults().setObject(urltxtfield.text, forKey: "urltxtfield")
NSUserDefaults.standardUserDefaults().synchronize()
}
override func viewDidLoad() {
super.viewDidLoad()
if NSUserDefaults.standardUserDefaults().objectForKey("urltxtfield") != nil {
urltxtfield.text = NSUserDefaults.standardUserDefaults().objectForKey("urltxtfield") as? String
} else {
urltxtfield.placeholder = "urltxtfield"
}
}
And it's ok with save. But how to make URL work with LeftVC webview?
This pic to make you understand me:
In your LeftVC (webView), you first need to get the NSUserDefaults and then make a request with your webView.
let prefs = NSUserDefaults.standardUserDefaults()
if let url = prefs.stringForKey("urltxtfield"){
// You have an URL and can make the request
let requestURL = NSURL(string: url)
let request = NSURLRequest(URL: requestURL!)
webView.loadRequest(request)
}else{
// Nothing stored in NSUserDefaults
}
Update
After I got the project I updated the reference to the webView from strong to weak and I added the temporary code
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
In info.plist to allow you to browse on websites (you have to check if you want this and I can recommend you to read more about it).
here: some sample of code to call load request to UIWebview when user enter url that urlstring it pass here as parameter Instead of google.com:
UIWebView.loadRequest(webviewInstance)(NSURLRequest(URL: NSURL(string: "google.cam")!))
OR
let url = NSURL (string: "http://www.google.com");
let requestObj = NSURLRequest(URL: url!);
myWebView.loadRequest(requestObj);