所以我正在练习用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)
}
2条答案
按热度按时间rqqzpn5f1#
按照API响应修改变量名称和数据类型。
您也可以使用CodingKey,并在初始化期间更改响应。
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") }
}