0

I'm trying to access an API I made in PHP. It works fine in browser, but I can't get this code to fetch any sort of data from any given webpage.

var jsonData: NSData = NSData(contentsOfURL: NSURL(string: "http://www.google.com"))
let string1 = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
println(string1)

What am I doing wrong here?

Update: Here's the output after changing encoding.

enter image description here

Also, NSURLConnection doesn't start when I do that either. Might be a related issue.

User
  • 23,729
  • 38
  • 124
  • 207

1 Answers1

3

the code is correct but the data isn't in UTF it seems so it fails to make the NSString.

fails in swift & objC

for that server data is in NSISOLatin2StringEncoding

it differs based on the HTTP endpoint and normally UTF8 is fine


    var jsonData: NSData = NSData(contentsOfURL: NSURL(string: "https://www.google.com"))
    let string1 = NSString(data: jsonData, encoding: NSISOLatin1StringEncoding)
    println(string1)

shows the page's sourcecode

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • The error is gone, but it prints a blank line with all URLs I try. – User Sep 20 '14 at 16:29
  • I just copied that code and pasted it. I don't have any output but a blank line. I added the screenshot of the console box. Maybe an Xcode problem? Even though its a fresh install. – User Sep 20 '14 at 17:13
  • ah it is ISOLatin for me -- encoding may differ again for you - based on your region -> google does a lot of forwarding. – Daij-Djan Sep 20 '14 at 17:16
  • use an api you control / of which you know the encoding ;) – Daij-Djan Sep 20 '14 at 17:17
  • Yeah, I'm trying to use one that I made, a straight up PHP page that `echo`s ASCII-compliant characters. I also tried other people's. – User Sep 20 '14 at 17:37
  • NSURLConnection won't work either. Could be a related problem. – User Sep 20 '14 at 19:54
  • Yeah lol, it's on the same computer as this. Maybe I should reboot or something. – User Sep 20 '14 at 20:00
  • Unreal, restarting Xcode made it start to work. Might be a bug in Xcode 6? Haha, thanks for your help. Back to coding! – User Sep 20 '14 at 20:07
  • yes, xcode6 does have a few rough edges here and there :) glad it works – Daij-Djan Sep 20 '14 at 20:08