我在课程 - >>中完成了所有工作letsbuildthatapp
但是在课程中 Brian 使用 JSON 。我想使用 FirebaseDatabase 。 如何从 Firebase 下载数据?可能需要使用较少数量的类,但我无法弄清楚如何更改 Firebase 上的下载量。
JSON 结构就像一节课(为了便于理解,我略微削减了 JSON 文件)。 JSON 和 Firebase :
{
"categories" : [ {
"apps" : {
"4" : {
"Category" : "Entertainment",
"Id" : 1,
"ImageName" : "frozen",
"Name" : "Disney Build It: Frozen",
"Price" : 3.99,
"Screenshots" : [ "frozen_screenshot1", "frozen_screenshot2", "frozen_screenshot3", "frozen_screenshot4", "frozen_screenshot5" ]
},
"7" : {
"Category" : "Health & Fitness",
"ImageName" : "today",
"Name" : "Today: Habit tracker for your daily goals and routines"
}
},
"name" : "Best New Apps",
"type" : ""
}, {
"apps" : [ {
"Category" : "Games",
"Id" : 2,
"ImageName" : "telepaint",
"Name" : "telepaint",
"Price" : 2.99,
"Screenshots" : [ "telepaint1", "telepaint2", "telepaint3", "telepaint4", "telepaint5" ]
}, null, null, {
"Category" : "Games",
"ImageName" : "beatstomper",
"Name" : "Beat Stomper",
"Price" : 1.99
} ],
"name" : "Best New Games",
"type" : ""
} ]
}
课程应用
class App {
var id: String?
var imageName: String?
var screenshots = [String]()
init (from json: JSON) {
id = json["Id"].stringValue
imageName = json["ImageName"].stringValue
}
func updateValue(completion: (() -> Void)?) {
guard let appID = id else { return }
let url = "https://api.letsbuildthatapp.com/appstore/appdetail?id=\(appID)"
Alamofire.request(url).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
for ssj in json["Screenshots"].arrayValue {
if let ss = ssj.string {
self.screenshots.append(ss)
}
}
case .failure(let error):
print(error)
}
completion?()
}
}
}
班级类别:
class Category {
var apps = [App]()
init (from json: JSON) {
for appData in json["apps"].arrayValue {
let app = App(from: appData)
apps.append(app)
}
}
}
班级类别:
class Categoris {
private let url = "https://api.letsbuildthatapp.com/appstore/featured"
private var cats = [Category]()
func numberOfCats() -> Int {
return cats.count
}
func fetchCat(from indexPath: IndexPath) -> Category {
return cats[indexPath.row]
}
func loadData(completion: (() -> Void)?) {
Alamofire.request(url).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
for catData in json["categories"].arrayValue {
let cat = Category(from: catData)
self.cats.append(cat)
}
case .failure(let error):
print(error)
}
completion?()
}
}
}