3
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

Community
  • 1
  • 1
spin_eight
  • 3,925
  • 10
  • 39
  • 61
  • do you have webview? – Özgür Ersil Aug 09 '16 at 10:56
  • @ÖzgürErsil I wan't to get text(content) within html page, make some actions with it and display in own TextView – spin_eight Aug 09 '16 at 11:00
  • Possible duplicate of [How To Get HTML source from URL with Swift](http://stackoverflow.com/questions/26134884/how-to-get-html-source-from-url-with-swift) – Mr. Xcoder Aug 09 '16 at 11:01
  • I tried in Objective-C, I didn't get any issue. Did you allowed the App Transport Security? Also, there the `NSString` method equivalent allow the use a NSError (throw), maybe the `String` one does to, could you check if there is an error? – Larme Aug 09 '16 at 11:29
  • @Larme I think I don't need App Transport Security for https, which I mentioned in my url, only for http. – spin_eight Aug 09 '16 at 11:38

3 Answers3

3

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!

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
  • this is exactly that I am doing, and I getting the result: text of link, but instead I need text of html page. Also "http" - requires special permission and you haven't mentioned it at all. – spin_eight Aug 09 '16 at 11:08
1

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.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
-1

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)
      }
    }
spin_eight
  • 3,925
  • 10
  • 39
  • 61