Coen Walter Coen Walter -4 years ago 74
JSON Question

Get specific json data in Swift

I'm using a API that gets a list of the crew from a movie. To get that i'm using this function:

MovieMDB.credits(apiKey, movieID: movieID){
apiReturn, credits in
if let credits = credits{
for crew in credits.crew{
print(crew.job)
print(crew.name)

}

}
}


This prints a list of jobs and crew members. But I only want the producer of this movie.

The function that's called:

///Get the cast and crew information for a specific movie id.
public class func credits(_ api_key: String!, movieID: Int!, completion: @escaping (_ clientReturn: ClientReturn, _ credits: MovieCreditsMDB?) -> ()) -> (){
Client.Movies(String(movieID) + "/credits", api_key: api_key, page: nil, language: nil){
apiReturn in
var credits: MovieCreditsMDB?
if(apiReturn.error == nil){
credits = MovieCreditsMDB.init(results: apiReturn.json!)
}
completion(apiReturn, credits)
}
}


This is the beginning of the json file:

{
"id": 550,
"cast": [
{
"cast_id": 4,
"character": "The Narrator",
"credit_id": "52fe4250c3a36847f80149f3",
"gender": 2,
"id": 819,
"name": "Edward Norton",
"order": 0,
"profile_path": "/eIkFHNlfretLS1spAcIoihKUS62.jpg"
},


Here is the data I want:

"crew": [
{
"credit_id": "56380f0cc3a3681b5c0200be",
"department": "Writing",
"gender": 0,
"id": 7469,
"job": "Screenplay",
"name": "Jim Uhls",
"profile_path": null
},
{
"credit_id": "52fe4250c3a36847f8014a05",
"department": "Production",
"gender": 0,
"id": 7474,
"job": "Producer",
"name": "Ross Grayson Bell",
"profile_path": null


I need the name of the producer. Does someone know how to get that specific data?
Link to json go to responses > example

Answer Source

You just need to filter the result and only use/return the one that you want.

Once you have the list of all credits, just look for the one with the job of producer

 MovieMDB.credits(apiKey, movieID: movieID){
        apiReturn, credits in

        var producer: [String:AnyObject]?
        if let credits = credits {
            for crew in credits.crew {
                if crew.job == "Producer" {
                     producer = crew
                     break
                }
            }
        }
        // here check producer is not nil to ensure it was found
    }

you could also shorten this code using filter:

MovieMDB.credits(apiKey, movieID: movieID){
    apiReturn, credits in


    if let credits = credits {
        let producer = credits.filter({ $0.job == "Producer" })
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download