0

Hello Guys i need help I'm trying to save json data in an array but i'm not getting it properly can anyone help me here is the complete code

let url = URL(string: "http://localhost:3000/liveData/device/20042")
    URLSession.shared.dataTask(with: url!, completionHandler: {
        (data, response, error) in
        if(error != nil){
            print("error")
        }else{
            do{
                let json = try JSONSerialization.jsonObject(with: data!, options:[]) as! [[String: Any]]

                print(json)

                    for item in json {

                    if let title = item["BV"] as? String {
                        self.userIdArray.append(title)
                    }

                    if let title = item["BC"] as? String {
                        self.userIdArray.append(title)
                    }

                    if let title = item["SV"] as? String {
                        self.userIdArray.append(title)
                    }

                    if let title = item["SC"] as? String {
                        self.userIdArray.append(title)
                    }

                }

                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                }

            }catch let error as NSError{
                print(error)
            }
        }
    }).resume()

I want to save json data in userIdArray can anyone help me, Thank you.

{
"SV" : 0,
"SC" : 0,
"BV" : 14.807,
"BC" : 0.024,
}

This is the output json

5
  • stackoverflow.com/questions/42081141/… Commented Sep 4, 2018 at 7:25
  • What are you getting after printing JSON? Commented Sep 4, 2018 at 7:26
  • "but i'm not getting it properly": How is that? What's your JSON (you did print(json), what's the output)? How can we help you to know what's wrong if you can't tell us what's the expected output and the current one? Commented Sep 4, 2018 at 8:43
  • After seeing the edit: if let title = item["SC"] as? String shouldn't work because of the as? String. You have Double values. Instead: if let title = item["SC"] as? Double { self.userIdArray.append(String(title)}}? Commented Sep 4, 2018 at 9:39
  • ohh yeah that's correct Thank you so much @Larme Commented Sep 4, 2018 at 9:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.