从json文件swift中获取特定的值

时间:2018-12-12 18:00:30

标签: ios json swift instagram-api

我正在尝试使用其API获取instagram用户名,这是我的代码:

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()
}

print语句返回以下内容,因此它可以正常工作,但是随后我不知道如何访问和存储用户名值,并且我不理解其他人对类似主题的答复:

{
  "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
  }
}

2 个答案:

答案 0 :(得分:2)

您可以使用jsonSerialization将json对象转换为swift字典对象。

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()

答案 1 :(得分:1)

另一种选择是在Swift中使用Codable系统:

struct Counts: Codable {
    enum CodingKeys: String, CodingKey {
        case followedBy = "followed_by"
        case follows
        case media
    }
    let followedBy: Int
    let follows: Int
    let media: Int
}

struct InstagramUser: Codable {
    enum CodingKeys: String, CodingKey {
        case bio
        case counts
        case fullName = "full_name"
        case id
        case isBusiness = "is_business"
        case profilePicture = "profile_picture"
        case username
        case website
    }

    let bio: String
    let counts: Counts
    let fullName: String
    let id: String
    let isBusiness: Bool
    let profilePicture: String
    let username: String
    let website: String
}

struct Meta: Codable {
    let code: Int
}

struct Output: Codable {
    enum CodingKeys: String, CodingKey {
        case user = "data"
        case meta
    }
    let user: InstagramUser
    let meta: Meta
}

现在您可以在块内使用:

let ouptut = try! JSONDecoder().decode(Output.self, from: data)
let fullName = output.user.fullName