首页 > 解决方案 > 如何使用 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 可在此处找到。在这里可以找到我用来帮助我编写代码的教程。

标签: swiftxcodeapi

解决方案


完全按照您的 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)")
}

推荐阅读