Search code examples
iosjsonswiftinstagram-api

Getting specific value from json file swift


I'm trying to get an instagram username, using their API, here's my code :

private func getUserInfo() {

    let request = NSMutableURLRequest(url: NSURL(string: "https://api.instagram.com/v1/users/self/?access_token=\(Settings.Access_Token)")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        guard let data = data else { return }
        print(String(data: data, encoding: .utf8)!)
    })
    dataTask.resume()
}

The print statement returns the following so it works, but then I don't know how to access and store the username value and I don't understand others response to similar topics :

{
  "data": {
    "id": "253876051",
    "username": "bruncheveuxcourtsyeuxverts",
    "profile_picture": "https:\/\/scontent.cdninstagram.com\/vp\/7eb0427fdd53a5b319d04c22af1c9f63\/5C977089\/t51.2885-19\/s150x150\/46724860_307687986508947_185550859294212096_n.jpg?_nc_ht=scontent.cdninstagram.com",
    "full_name": "Lo\u00efc Buckwell",
    "bio": "Gogole de p\u00e8re en fils",
    "website": "",
    "is_business": false,
    "counts": {
      "media": 16,
      "follows": 106,
      "followed_by": 406
    }
  },
  "meta": {
    "code": 200
  }
}

Solution

  • You can use jsonSerialization to convert the json object to swift dictionary object.

    For example
    
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let dataResponse = data,
              error == nil else {
              print(error?.localizedDescription ?? "Response Error")
              return }  
        do{ 
            //here dataResponse received from a network request 
            let jsonResponse = try JSONSerialization.jsonObject(with:
                                   dataResponse, options: []) 
            print(jsonResponse) //Response result 
         } catch let parsingError {
            print("Error", parsingError) 
       }
    }
    task.resume()