Reputation: 27
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()
}
}
Upvotes: 0
Views: 464
Reputation: 773
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
}
}
}
}
Upvotes: 2