xcode 如何使用Swift进行API调用?

mnowg1ta  于 2022-11-30  发布在  Swift
关注(0)|答案(2)|浏览(266)

所以我正在练习用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是here。我用来帮助我编写代码的教程是here

rqqzpn5f

rqqzpn5f1#

按照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)")
}
doinxwow

doinxwow2#

导入UIKit
class ApiManager: NSObject { static func postApiRequest(url: String,parameters:[String: Any],completion: @escaping([String: Any])-> Void) { let session = URLSession.shared let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") do{ request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions()) let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in if let response = response { let nsHTTPResponse = response as! HTTPURLResponse let statusCode = nsHTTPResponse.statusCode print ("status code = (statusCode)") } if let error = error { print ("(error)") } if let data = data { do{ let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) print ("data = (jsonResponse)") }catch _ { print ("OOps not good JSON formatted response") } } }) task.resume() }catch _ { print ("Oops something happened buddy") }

}

}

enter code here

相关问题