0

I'm trying to read data from a webpage and I'm using the NSString initialiser - init(contentsOfURL since there's only one sentence on that page that I need to display in a label.

if var optUrl = NSURL(string: "www.example.com/examplepage.php"){
        if let optStr = NSString(contentsOfURL: optUrl, encoding: NSUTF8StringEncoding, error: nil){
            println(optStr)
            songLabel.text = optStr
        }

    }

When I run the code in the emulator in Xcode, the println does print the sentence, but it won't show in the label... If I change the code to songLabel.text = "Now playing: \(optStr)", I get to see Now playing: but not the value of optStr which is shown by the println.

Is there something I did wrong?

Daniel Galasko
  • 23,617
  • 8
  • 77
  • 97
m1ch14l
  • 11
  • 4

1 Answers1

0

Conclusion

Turns out that everything was working, the string was preceded by a newline character and since the labels number of lines was 0 the text wasn't visible. Breakpoints are always your friend.


Irrelevant

Looks like you need to add http://

This worked in a playground for me for a php file

if var optUrl = NSURL(string: "http://php.net/manual/en/function.file.php") {
    println(optUrl)
    var error: NSError? = nil
    if let optStr = NSString(contentsOfURL: optUrl, encoding: NSUTF8StringEncoding, error: &error) {
        println(optStr)
    }
    print(error)
}

Edit

Its also possible that perhaps your string is empty seeing as you stated that setting "Now playing: (optStr)" results in "Now playing:"

Validate your contents in a playground, but you should at least be able to check

countElements(optStr) > 0
Daniel Galasko
  • 23,617
  • 8
  • 77
  • 97
  • The `println` does indeed work, but I have to put the `optStr` into a label, which doens't work – m1ch14l Feb 10 '15 at 13:14
  • @m1ch14l well you can always place a breakpoint on the line and confirm, alternatively you can place the set text into a NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in //set text here } – Daniel Galasko Feb 10 '15 at 13:18
  • @m1ch14l I updated my answer, its possible your php is actually empty – Daniel Galasko Feb 10 '15 at 13:24
  • 1
    Got it working, I placed a breakpoint at `songLabel.text = optStr` and noticed that `optStr` contained a `\n` at the beginning of the string. I changed the lines of the label to 2 and now I can see the string... I feel stupid and dumb :p Thanks for the help ;) – m1ch14l Feb 10 '15 at 13:24
  • @m1ch14l haha awesome! – Daniel Galasko Feb 10 '15 at 13:24