gariva
gariva

Reputation: 45

swift NSURL gets back an "unable to read data" message even with https://

I am trying to learn iOS following a course and they ask to do the following:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //var string1 = "http://www.google.com"
    //var string1 = "https://www.weather-forecast.com/locations/San-Antonio/forecasts/latest"
    //var url = NSURL(string: string1)
    var url = NSURL(string: "https://google.com")

    print(url)

        if url != nil {

            let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

                var urlError = false

                if error == nil {

                    var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    print(urlContent)


                } else {

                    urlError = true

                }

                if urlError == true {
                    self.showError()
                }
        })

            task.resume()

        } else {

            showError()

    }
}

the app doesn't show any web page content and when debugging I find that the object for the url says that it is "unable to read data"

I have tried with http and https. I have tried with different web sites.

I have tried the address in the safari of the simulator and it loads.

Can someone tell me why is this not working

Thanks in advance. gariva

Upvotes: 2

Views: 1859

Answers (2)

user3820674
user3820674

Reputation: 262

For display web page you should use UIWebView element. Something like this:

        let url = NSURL(string: "https://google.com")
        let webView = UIWebView(frame: self.view.frame)
        self.view.addSubview(webView)
        webView.loadRequest(NSURLRequest(URL: url!))

Upvotes: -1

Rafał Sroka
Rafał Sroka

Reputation: 40030

You're using wrong encoding. The webpage you're trying to fetch (http://www.google.com/) uses ISO-8859-1.

enter image description here

I was able to reproduce your issue. Fetch worked when I changed encoding. Try this:

 var urlContent = NSString(data: data!, encoding: NSISOLatin1StringEncoding)

Upvotes: 4

Related Questions