Search code examples
uber-apiswift2

How do I parse a Dictionary which come in 2 response from a URI


I have been integrating UBER ride API in my app. I am a beginner in swift and I have still not fully understood the concept of parsing JSON/Dictionary etc from an URI. When I book the uber I get a response like this

{"status":"processing","product_id":"28d5215d","destination":{"latitude":10.0216,"longitude":76.27394},"driver":null,"pickup":{"latitude":10.01319,"longitude":76.27691},"request_id":"5aa6fe30-9eed-4f19-8a8f-c0ed8aa1bfae","location":null,"vehicle":null,"shared":false}

Then when a driver accepts my request I get the response like this from the same dataRequestWithURL. I do this by calling the same dataTask in its response till the driver accepts it.

{"status":"accepted","product_id":"6fd04ea","destination":{"latitude":10.0216,"eta":8,"longitude":76.27394},"driver":{"phone_number":"+919562117444","rating":4.62,"picture_url":"https:\/\/d1w2poirtb3as9.cloudfront.net\/token.jpeg","name":"FULL NAME","sms_number":null},"pickup":{"latitude":10.01319,"eta":5,"longitude":76.27691},"request_id":"5aa6fe30-9eed-4f19-8a8f-c0ed8aa1bfae","location":{"latitude":10.0062228,"bearing":249,"longitude":76.2780944},"vehicle":{"make":"Maruti Suzuki","picture_url":null,"model":"Ritz","license_plate":"LICENSE#"},"shared":false}

How do I parse this based on the condition.

This is my code right now.

if let dict = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? [String: AnyObject],
                let status = dict["status"] as? String,
                let driver = fareDict["driver"] as? [String:AnyObject] {
                    do 
                   {
                    //assign the value and update UI

                    } catch let error {
                        print("OK")
                    }


                }

Solution

  • If I understand you correctly, you only want to parse the dictionary when the ride has been accepted?

    If so, you can do the following:

    //MARK : Check if rider has accepted the ride
                    if let dict = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? [String: AnyObject],
                        let status = dict["status"] as? String{
                        if status == "accepted"
                        {
    
                            print("Accepted")
    
    
                        }
                        else
                        {
                         self.getUberRideLive()
    
                        }
    
    
                    }