-3

My PHP script returns response like

Optional({
    message = "";
    response =     {
        "session_id" = mf6pnrsf931m96g0hc3n4pjbw3;
        "session_name" = d72d1363f44031cac4148b0e6fa789d6;
    };
    "session_valid" = true;
    success = true;
})

How can I access/print the value of session id/session name in Swift 2.2? I dont have any problem in storing the value returned by 'session_valid'

lubilis
  • 3,942
  • 4
  • 31
  • 54
F Gala
  • 1
  • 4
  • 2
    This format is called JSON. Google `Swift parse JSON` – Pekka Sep 19 '16 at 08:06
  • Possible duplicate of [How to parse a JSON file in swift?](http://stackoverflow.com/questions/24013410/how-to-parse-a-json-file-in-swift) – Pekka Sep 19 '16 at 08:06
  • No, no..I am able to access 'the_message' from the data, but I dont know how to print 'value1' or 'value2' – F Gala Sep 19 '16 at 08:13
  • So you already have Swift code accessing the data? Can you show it? – Pekka Sep 19 '16 at 08:14
  • See this..I know how this works.. var json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary if let parseJSON = json { message = parseJSON[“message"] as? String } – F Gala Sep 19 '16 at 08:19
  • key1 and key2 are actually 2 parameters which the response field is returning..i dont know how to access them – F Gala Sep 19 '16 at 08:20
  • 2
    @FGala you need to edit the question and put your code there in proper formatting. – Umair Afzal Sep 19 '16 at 08:23
  • 2
    Read the Apple article [Working with JSON in Swift](https://developer.apple.com/swift/blog/?id=37). It's for Swift 3 but you can learn the proposed procedures. – vadian Sep 19 '16 at 08:25

2 Answers2

1
     var parseObject: AnyObject?

    let data = NSData() //response data that you get from script(use this instead of "data"). if response is string then you need to convert the string to data


    do{
        parseObject = try NSJSONSerialization.JSONObjectWithData(data, options: [])
    }catch let error as NSError{
        print(error)
    }

    let objectDic = parseObject as! NSDictionary

    if let status = objectDic.objectForKey("success") as? Bool  {
        if status == true {
            if let validSession = objectDic.objectForKey("session_valid") as? Bool{

                if validSession {
                    let response = objectDic.objectForKey("response") as? NSDictionary

                    print(response)
                }

            }
        }

    }
  • 2
    That doesn’t really seem to address the OP’s situation, though. Can you edit it to parse the specific bits they need? They already know how to parse JSON in general. – Pekka Sep 19 '16 at 08:25
  • @AsaduzzamanShuvro..your answer led me to what i needed..thank u:) – F Gala Sep 21 '16 at 08:20
0

What I needed was this-

let response = objectDic.objectForKey("response") as? NSDictionary

followed by

let session_name = response.objectForKey("session_name") as! String
F Gala
  • 1
  • 4