首页 > 解决方案 > 如何打印一些数据值?[迅速]

问题描述

我现在正在使用URLSession。我只想在这里打印数据值profile中的userIdprofile中的值。我怎样才能打印它?

我的一些代码

if let httpResponse = response as? HTTPURLResponse {
      print( httpResponse.allHeaderFields )
                                          
      guard let data = data else {return}
      print( String (data: data, encoding: .utf8) ?? "" )
                
      let profile = "{\"profile\":\"\(data.profile ?? "")}" // ERROR [Value of type 'Data' has no member 'profile']
                
      }

print (String (data: data, encoding: .utf8) ??"") <当我运行这段代码时,我得到这样的结果。我想显示userId不包括userId。谢谢阅读。 profileonly the profile在此处输入图像描述

标签: iosswiftprinting

解决方案


我会定义一个符合 Codable 协议的类型,并使用 JSONDecoder 将您的数据解码为用户友好的内容。

struct UserData: Codable {
    let userId: String
    let profile: String
}

以下是解码数据的方法:

if let httpResponse = response as? HTTPURLResponse {

    guard let data = data else { return }

    let decoder = JSONDecoder()
    do {
        let userData = try decoder.decode(UserData.self, from: data)
        print(userData.profile)
    } catch {
        print("Error: \(error)")
    }
}

推荐阅读