【发布时间】:2018-05-30 20:36:34
【问题描述】:
我必须解析并发现一种优雅的方式来处理我的解析数据,并使用它来正确填充 UIElement,例如 UITableViews、UICollectionViews 等。我将在下面发布我的解析方式以及 JSON 文件.
import Foundation
struct Contents : Decodable {
let data : [Content]
}
struct Content : Decodable {
let id : Int
let descricao : String
let urlImagem : String
}
API 响应文件:
import Foundation
var audioBook = [Content]()
func getAudiobooksAPI() {
let url = URL(string: "https://alodjinha.herokuapp.com/categoria")
let session = URLSession.shared
guard let unwrappedURL = url else { print("Error unwrapping URL"); return }
let dataTask = session.dataTask(with: unwrappedURL) { (data, response, error) in
guard let unwrappedDAta = data else { print("Error unwrapping data"); return }
do {
let posts2 = try JSONDecoder().decode(Contents.self, from: unwrappedDAta)
audioBook = posts2.data
} catch {
print("Could not get API data. \(error), \(error.localizedDescription)")
}
}
dataTask.resume()
}
TableView 文件:
如何使用我解析的数据进行填充?我真的很难做到这一点。我需要一个解释来指导我如何使用优雅的方式以及作为高级开发人员来做到这一点。
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource {
@IBOutlet var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
getAudiobooksAPI()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ?????
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell
???????
return cell
}
}
JSON:
【问题讨论】:
-
请删除所有这些空行。你为什么这样做?
-
你好@meaning-matters!我这样做只是为了你们可能会更好地可视化代码
标签: json swift uitableview