Swift get content of html from url - html

let myURLString = "https://en.wiktionary.org/wiki/see"
if let myURL = NSURL(string: myURLString) {
let myHTMLString = String(contentsOfURL: myURL, encoding: String.Encoding.utf8)
print("HTML : \(myHTMLString)")
}
And I got printed:
HTML : (https://en.wiktionary.org/wiki/see, Unicode (UTF-8))
But instead I need html content.
What I am doing wrong?
Update:
As a source for the code I used: How To Get HTML source from URL with Swift
Please, read my question with more attention, as the result I got text of link, but instead I need text of html page

Try this:
let myURLString = "http://google.com"
guard let myURL = NSURL(string: myURLString) else {
print("Error: \(myURLString) doesn't seem to be a valid URL")
return
}
do {
let myHTMLString = try String(contentsOfURL: myURL)
print("HTML : \(myHTMLString)")
} catch let error as NSError {
print("Error: \(error)")
}
Hope this helps!

To retrieve the HTML of the webpage referenced by a url you just need to
let myURLString = "https://en.wiktionary.org/wiki/see"
if let
url = NSURL(string: myURLString),
html = try? String(contentsOfURL: url) {
print(html)
}
I tested this code in my Playground and it is retrieving the full HTML of the web page.

Solution: instead of String, use NSString
let myURLString = "https://en.wiktionary.org/wiki/see"
if let myURL = NSURL(string: myURLString) {
do {
let myHTMLString = try NSString(contentsOf: myURL as URL, encoding: String.Encoding.utf8.rawValue)
print("html \(myHTMLString)")
} catch {
print(error)
}
}

Related

How to set the timeout in swift trying to catch html code?

I'm trying too get the html code from a specific URL with this code:
guard let myURL = URL(string: myURLString) else {
print("Error: \(myURLString) doesn't seem to be a valid URL")
return myLinksArray
}
do {
myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
print("HTML : \(myHTMLString)")
} catch let error {
print("Error: \(error)")
}
but in this way I'm unable to set a timeout. Some websites require too much time to get response.
What's the best way to solve the problem?
Thanks in advance
Have you considered creating an URLSession dataTask, I believe it would be a better approach. You can create a custom URLSessionConfiguration and use it to specify the timeoutIntervalForRequest or timeoutIntervalForResource according to your needs like this:
guard let myURL = URL(string: myURLString) else {
print("Error: \(myURLString) doesn't seem to be a valid URL")
fatalError()
}
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 15 // seconds
sessionConfig.timeoutIntervalForResource = 15 // seconds
let dataTask = URLSession(configuration: sessionConfig).dataTask(with: myURL) { (data, urlResponse, error) in
guard let data = data else { return }
let myHTMLString = String(data: data, encoding: .ascii)
print("HTML : \(myHTMLString ?? "")")
}
dataTask.resume() // start the request

Swift JSON Parsing with a filter in url

I am trying to parse JSON, everything works fine, but when I try to give a filter with the url, it says found nil while unwrapping an optional value. I was wondering if I should give the filters in some other way. PS.. The url works fine when I use it in the browser
this is how the url with filter looks like:
https://start.jamespro.nl/v4/api/json/tasks/?filter=[{"column":"Date","operator":"=","value":"2017-08-04"}, {"column":"UserId","operator":"=","value":"2"}]
and this is my whole code:
func apiRequestTasks(url: String) {
apiRequestHeader(userName: "*******", passWord: "******")
var running = false
let urlProjects = NSURL(string: url)
let task = session?.dataTask(with: urlProjects! as URL) {
( data, response, error) in
if let taskHeader = response as? HTTPURLResponse {
print(taskHeader.statusCode)
}
if error != nil {
print("There is an error!!!")
print(error ?? "")
} else {
if let content = data {
do {
let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
print(dictionary)
}
catch {
print("Error: Could not get any data")
}
}
}
running = false
}
running = true
task?.resume()
while running {
print("waiting...")
sleep(1)
}
}
I think the problem is the way you create your URL, try something like this:
let filters = "[\"column\":\"Date\",\"operator\":\"=\",\"value\":\"2017-08-04\"}, {\"column\":\"UserId\",\"operator\":\"=\",\"value\":\"2\"}]"
if var url = URLComponents(string: "https://start.jamespro.nl/v4/api/json/tasks") {
url.query = "filter=:\(filters)"
print ("url", url.string ? "invalid url")
}
I just encoded the filter part of my url and it worked. But thanx for the reactions !!!
let filter = "[{\"column\":\"Date\",\"operator\":\"=\",\"value\":\"2017-08-04\"}, {\"column\":\"UserId\",\"operator\":\"=\",\"value\":\"2\"}]"
let encodedFilter = filter.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
let baseUrl = "https://start.jamespro.nl/v4/api/json/tasks/?filter="
let url = baseUrl + encodedFilter!
apiRequestTasks(url: url)

How to get dynamic loaded HTML in Swift

I can use Alamofire to return the HTML of a page, but some div's content is empty.
If I open chrome's developer console I can see them in ELements tab rather than Source tab.
How can I get those contents in Swift?
Look this method :
+ stringWithContentsOfURL:encoding:error (docs)
//the content url
let urlString = "https://google.com"
guard let theURL = URL(string: urlString) else {
print("Error: \(urlString) doesn't seem to be a valid URL")
return
}
do {
let myHTMLString = try String(contentsOf: theURL, encoding: .ascii)
print("html : \(myHTMLString)")
} catch let error {
print("Error: \(error)")
}

how to load local html file to string variable in ios swift?

i want to load my local html file into a string variable. i don't know how to do it. please help me.
i found below link but it load it from online url.
Swift & UIWebView element to hide
Copy the html into your project directory and use this code :
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
var htmlFile = NSBundle.mainBundle().pathForResource("MyHtmlFile", ofType: "html")
var htmlString = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
webView.loadHTMLString(htmlString!, baseURL: nil)
}
In Swift 3:
let htmlFile = Bundle.main.path(forResource:"MyHtmlFile", ofType: "html")
let htmlString = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
webView.loadHTMLString(htmlString!, baseURL: nil)
I recommend using optional chaining instead of force unwrapping htmlString as above.
You can write some utility method like this and get the html string and load it to webview. I used the URL approach here
private func getHTML() -> String {
var html = ""
if let htmlPathURL = Bundle.main.url(forResource: "test", withExtension: "html"){
do {
html = try String(contentsOf: htmlPathURL, encoding: .utf8)
} catch {
print("Unable to get the file.")
}
}
return html
}
Swift 3 syntax:
guard
let file = Bundle.main.path(forResource: "agreement", ofType: "html"),
let html = try? String(contentsOfFile: file, encoding: String.Encoding.utf8)
else {
return
}
webView.loadHTMLString(html, baseURL: nil)
Simple answer
let indexPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "/")
if let indexPath = indexPath
{
do
{
let htmlContent = try String(contentsOfFile: indexPath, encoding: String.Encoding.utf8)
let base = Bundle.main.resourceURL
self.webView.loadHTMLString(htmlContent, baseURL: base)
}
catch let err as NSError
{
print(err.debugDescription)
}
}

HTML code in Swift String (not NSString)

I am downloading HTML source code of a webpage this way:
let url = NSURL(string: "http://www.example.com")
var error: NSError?
let html = NSString(contentsOfURL: url!, encoding: NSUTF8StringEncoding, error: &error)
if (error != nil) {
println("whoops, something went wrong")
} else {
println(html!)
}
But I would like to get it as String instead of NSString. Is there any way?
Swift's String also accepts the same initializer:
let html = String(contentsOfURL: url!, encoding: NSUTF8StringEncoding, error: &error)
I would suggest to use safe unwrapping with if let for your values:
var error: NSError?
if let url = NSURL(string: "http://www.example.com"), let html = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error) {
if error != nil {
println(error)
} else {
println(html)
}
}
Last note: no need to use brackets around the condition in Swift.
Update for Swift 2 (Xcode 7)
if let url = NSURL(string: "http://www.example.com"),
let html = try? String(contentsOfURL: url, encoding: NSUTF8StringEncoding) {
print(html)
}