-1

I have this JSON

{
  "chatUsers":"[
    {"id":"5","sender_id":"6","receiver_id":"1","content":"hi","datetime":"2016-11-19 00:00:00"},
    {"id":"4","sender_id":"1","receiver_id":"2","content":"hello","datetime":"2016-11-11 00:00:00"},
    {"id":"2","sender_id":"1","receiver_id":"3","content":"how are you","datetime":"2016-11-04 00:00:00"}
  ]",
  "chatsCount":3
}

now I have this code to get data from the url :

let StringUrl  = NSURL(string: url) as NSURL!
let Data = NSData(contentsOfURL: StringUrl) as NSData!
let ReadableData = JSON(data: Data)

let result =  ReadableData["chatUsers"][0]["id"].string! as String // this should gives 5

but it always gives this error :

fatal error: unexpectedly found nil while unwrapping an Optional value

any idea why ?

Madian Malfi
  • 595
  • 1
  • 8
  • 26
  • 2
    Set breakpoint, debug step by step. found out which one is nil – antonio081014 Nov 01 '16 at 18:17
  • json format is wrong , why backward slash is added to each key and value , no need to add this – Shobhakar Tiwari Nov 01 '16 at 18:18
  • 1
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – rmaddy Nov 01 '16 at 18:27
  • the backward slash is just to escape the quotes ("), anyway I removed the slashes but it still show the same error – Madian Malfi Nov 01 '16 at 18:34

1 Answers1

1

There's quite a bit wrong with the example you provided above, but for the sake of getting you moving in the right direction, let me give you a some advice and a quick solution to your issue.

First off, don't start your variables with an uppercase character. Its not a set in stone rule or anything, but it's better practice to use camelCase as it will make your code more readable and avoid confusion.

Secondly, you are doing lots of force casting and force unwrapping of optional values which will make your application prone to crashes due to the same error you are getting now. I would take a look at the following for some better guidance: https://stackoverflow.com/a/25195633/4660602

Third, when posting on SO, please make sure you clearly give your question context as some users may believe you are asking a question about what optionals are and why you are getting the fatal error: unexpectedly found nil while unwrapping an Optional value error.

With that said, in the future please make sure to take a look at the SwiftyJSON docs as they pretty clearly demonstrate how to use the library. The reason your code is not working is because you are handling the JSON incorrectly. Here is an updated example:

    let StringUrl  = NSURL(string: url) as NSURL!
    let Data = NSData(contentsOfURL: StringUrl) as NSData!
    let ReadableData = JSON(data: Data)
    let chatUsers = ReadableData["chatUsers"].arrayValue
    let result =  chatUsers[0]["id"].stringValue

or if you need to iterate through all the users:

    let StringUrl  = NSURL(string: url) as NSURL!
    let Data = NSData(contentsOfURL: StringUrl) as NSData!
    let ReadableData = JSON(data: Data)

    for chatUser in ReadableData["chatUsers"]{
        print(chatUser.1["id"].stringValue)
    }

Please note I did not update your variable identifiers to the correct convention for the sake of not confusing you, but you should really follow the correct convention as I mentioned in my first point.

Good luck.

EDIT: Forgot to mention that your JSON is incorrectly formatted. Please fix your JSON data to the correct JSON format so that SwiftyJSON can correctly interpret it. You are receiving index out of range because SwiftyJSON does NOT know chatUsers is an array because the square brackets are wrapped in double quotes when they should not be. So

"chatUsers":"[
{"id":"5","sender_id":"6","receiver_id":"1","content":"hi","datetime":"2016-11-19 00:00:00"},
{"id":"4","sender_id":"1","receiver_id":"2","content":"hello","datetime":"2016-11-11 00:00:00"},
{"id":"2","sender_id":"1","receiver_id":"3","content":"how are you","datetime":"2016-11-04 00:00:00"}
]" 

should be

"chatUsers": [
{"id":"5","sender_id":"6","receiver_id":"1","content":"hi","datetime":"2016-11-19 00:00:00"},
{"id":"4","sender_id":"1","receiver_id":"2","content":"hello","datetime":"2016-11-11 00:00:00"},
{"id":"2","sender_id":"1","receiver_id":"3","content":"how are you","datetime":"2016-11-04 00:00:00"}
]
Community
  • 1
  • 1
Geoherna
  • 3,523
  • 1
  • 24
  • 39
  • hi, thanks for your answer, i followed your code but it gives me : fatal error: Index out of range. – Madian Malfi Nov 01 '16 at 18:48
  • aha now that was the problem i was looking for :D, thank you very much for the answer and for the tips you provided they are really helpful – Madian Malfi Nov 01 '16 at 18:59
  • btw let chatUsers = ReadableData["chatUsers"][0]["id"] also works, is it better to use this way or the way you provided i dont know the difference – Madian Malfi Nov 01 '16 at 19:02