Men*_*aim 13 json ios swift codable decodable
我试图连接我的 API 数据以在单元格中查看它,但似乎我无法得到我的响应,而且总是== nil
下面的代码描述了 Country.SWIFT // Model.SWIFT // Response.SWIFT,它显示了如何我可以使用 Codable 获取 JSON 响应吗? CountryCell.SWIFT 展示了我如何使用它来调用 API API 图像的链接:
国家.SWIFT
struct Country: Decodable {
var CountryName = ""
var CountryImage = ""
var objectId = ""
// MARK: - Coding Keys
enum CodingKeys: String, CodingKey {
case CountryName = "CountryName"
case CountryImage = "CountryImage"
case objectId = "objectId"
}
//MARK: - Json Decoder
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// Parsing our attributes
self.CountryName = try container.decode(String.self, forKey: .CountryName)
self.CountryImage = try container.decode(String.self, forKey: .CountryImage)
self.objectId = try container.decode(String.self, forKey: .objectId)
}
}]
Run Code Online (Sandbox Code Playgroud)
模型.SWIFT
protocol ModelDelegate {
func countriesFetched (_ countries: [Country])
}
class Model {
//MARK: - Vars
var delegate: ModelDelegate?
// MARK: - Get Countries
func getCountries () {
// URL Object
let url = URL(string: Constants.API_URL)
guard url != nil else {return}
// URL Session object
let session = URLSession.shared
//Data Task from URLSession object
let dataTask = session.dataTask(with: url!) { (data, response, error) in
if error != nil || data == nil {
print(error!.localizedDescription)
return
}
print(data!)
do {
let decoder = JSONDecoder()
let response = try decoder.decode(Response.self, from: data!)
if response.items != nil {
DispatchQueue.main.async {
self.delegate?.countriesFetched(response.items!)
}
}
}
catch {
}
}
// start data task
dataTask.resume()
}
}
Run Code Online (Sandbox Code Playgroud)
响应.SWIFT
struct Response: Decodable {
var items: [Country]? = []
init(from decoder: Decoder) throws {
var itemsContrainer = try decoder.unkeyedContainer()
self.items = try itemsContrainer.decode([Country].self)
}
}
Run Code Online (Sandbox Code Playgroud)
CountryCell.SWIFT
class CountryCell: UICollectionViewCell {
//MARK: - Vars
var country: Country?
//MARK: - Outlets
@IBOutlet weak var imageViewCountryOutlet: UIImageView!
@IBOutlet weak var lblCountryNameOutlet: UILabel!
//MARK: - Creating Cell
func generateCell (_ myCountry: Country) {
self.country = myCountry
guard self.country != nil else { return }
lblCountryNameOutlet.text = country!.CountryName
guard self.country!.CountryImage != "" else {return}
let url = URL(string: self.country!.CountryImage)
guard url != nil else {return}
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) { (data, response, error) in
if error == nil || data != nil {
if url!.absoluteString != self.country!.CountryImage {
return
}
let image = UIImage(data: data!)
DispatchQueue.main.async {
self.imageViewCountryOutlet.image = image
}
}
}
dataTask.resume()
}
}
Run Code Online (Sandbox Code Playgroud)
不需要包装Response
类型,直接解码国家列表:
let decoder = JSONDecoder()
let items = try decoder.decode([Country].self, from: data!)
Run Code Online (Sandbox Code Playgroud)
在您的代码中,当您请求Response
for时unkeyedContainer
,预期的 JSON 结构将需要额外的嵌套数组。
catch
检查块中的解码错误
do {
...
}
catch {
print(error)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6151 次 |
最近记录: |