swift - 如何使用 Swift 进行 API 调用?
问题描述
所以我正在练习尝试使用 Swift 进行 API 调用。代码如下:
struct Example: Codable {
let userID: String
let ID: String
let title: String
let completed: String
}
func getJson(completion: @escaping (Example)-> ()) {
let urlString = "https://jsonplaceholder.typicode.com/todos/1"
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) {data, res, err in
if let data = data {
let decoder = JSONDecoder()
if let json: Example = try? decoder.decode(Example.self, from: data) {
completion(json)
}
}
}.resume()
}
}
getJson() { (json) in
print(json.ID)
}
但是,当调用 getJson 时,我无法打印出任何内容。我使用的示例 API 可在此处找到。在这里可以找到我用来帮助我编写代码的教程。
解决方案
完全按照您的 API 响应修改了您的变量名称和数据类型。
struct Example: Codable {
let userId: Int
let id: Int
let title: String
let completed: Bool
}
func getJson(completion: @escaping (Example)-> ()) {
let urlString = "https://jsonplaceholder.typicode.com/todos/1"
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) {data, res, err in
if let data = data {
let decoder = JSONDecoder()
do {
let json: Example = try! decoder.decode(Example.self, from: data)
completion(json)
}catch let error {
print(error.localizedDescription)
}
}
}.resume()
}
}
getJson() { (json) in
print(json.id)
}
您也可以使用 CodingKey 并且可以在初始化期间更改您的响应。
struct Example: Codable {
var userID: Int
var ID: Int
var title: String
var completed: Bool
enum CodingKeys: String, CodingKey {
case userID = "userId"
case ID = "id"
case title = "title"
case completed = "completed"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
userID = try values.decode(Int.self, forKey: .userID)
ID = try values.decode(Int.self, forKey: .ID)
title = try values.decode(String.self, forKey: .title)
completed = try values.decode(Bool.self, forKey: .completed)
title = "Title: \(title)"
}
}
func getJson(completion: @escaping (Example)-> ()) {
let urlString = "https://jsonplaceholder.typicode.com/todos/1"
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) {data, res, err in
if let data = data {
do {
let json: Example = try JSONDecoder().decode(Example.self, from: data)
completion(json)
}catch let error {
print(error.localizedDescription)
}
}
}.resume()
}
}
getJson() { (json) in
print("ID: \(json.ID) \(json.title)")
}
推荐阅读
- internet-explorer - Internet Explorer 将 Internet 页面视为“Intranet”页面并将其显示在兼容性视图中
- vue.js - 使用 vuejs 动态创建模型时如何从 DOM 控件中获取值
- python - 将原始 df 的列添加到 pyspark 中的 df
- ruby-on-rails - rake 路由 rails 中的错误 URI
- android - 在 Retrofit 中调用 Enqueue 函数
- ios - 如何防止选择器视图重复
- python - 无法使用 Pip 在 Python 3 中安装特定的库加密
- angular - Angular:设置它们后如何在组件中获取常量值?
- grep - 根据唯一 ID 计算文件中的文本匹配
- javascript - 固定定位元素顶部