0

how can I get the source code from an URL on the logs? This code is returning an error message on the logs instead of the HTML data.

Can you please help me and let me know what can I include/change?

Thank you!

import UIKit

class ViewController: UIViewController {

    @IBOutlet var textField: UITextField!

    @IBOutlet var display: UILabel!

    @IBAction func send(_ sender: Any) {


    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let url = URL (string: "https://www.weather-forecast.com/locations/London/forecasts/latest")!
        let request = NSMutableURLRequest(url:url)
        let task = URLSession.shared.dataTask (with:request as URLRequest) {
            data, response, error in

            if error != nil {
                print (error!)
            } else {
                if let unrappedData = data {
                    let dataString = NSString(data: unrappedData, encoding: String.Encoding.utf8.rawValue)
                    print (dataString!)
                }
            }

        }

        task.resume()
    }


}
1
  • Hello, please provide more details about the error, thank you. Commented May 4, 2020 at 0:14

1 Answer 1

2

We can get the html code from the URL like below,

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        DispatchQueue.global(qos: .background).async {
            // Background Thread
        let myURLString = "https://www.weather-forecast.com/locations/London/forecasts/latest"
        guard let myURL = URL(string: myURLString) else {
            print("Error: \(myURLString) doesn't seem to be a valid URL")
            return
        }

        do {
        let myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
        print("HTML : \(myHTMLString)")
        } catch let error {
        print("Error: \(error)")
        }

            DispatchQueue.main.async {
                // Run UI Updates or call completion block
            }
        }

    }

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