2

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.
    }


}
1
  • I think you got problem with your network. You can try to load it with Safari and see how it work? Commented Dec 23, 2015 at 7:48

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.