ios - 如何打印一些数据值?[迅速]
问题描述
我现在正在使用URLSession
。我只想在这里打印数据值profile
中的userId
和profile
中的值。我怎样才能打印它?
我的一些代码
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。谢谢阅读。
profile
only the profile
解决方案
我会定义一个符合 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)")
}
}
推荐阅读
- php - 如果数组有重复项,则键的空值
- google-apps-script - 为什么 Google 表格在发送电子邮件时缺少最后一封电子邮件?
- java - 防止应用程序从 java.io.IOException 崩溃:写入失败:ENOSPC(设备上没有剩余空间)
- generics - 为什么kotin在使用中缀时不能推断出类型?
- c# - 如何使用 AD 帐户保持我的应用程序“经过身份验证”?C#
- snakemake - Snakemake 运行子工作流程,但不运行我的工作流程的其余部分(直接转到全部规则)
- c++ - 如何从随机值范围内删除某个元素?
- visual-studio-code - 是否可以在不删除未使用的导入的情况下启用 source.organizeImports?
- android - 如何在颤振中创建三次单击按钮
- excel - 将文件夹中特定的excel文件复制到主工作表中