我有一个可从Firebase数据库加载一些数据(名称,描述和图像)的应用程序。我编写了加载名称和图像的代码(在Firebase中,我使用imageURL从另一个站点加载图像),现在我想从另一个站点加载描述。请帮我。谢谢。
这是我的代码:
import UIKit
class Service {
static let shared = Service()
let BASE_URL = "https://*******************.json"
func fetchProject(completion: @escaping ([Project]) -> ()) {
var projectArray = [Project]()
guard let url = URL(string: BASE_URL) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
// handle error
if let error = error {
print("Failed to fetch data with error: ", error.localizedDescription)
return
}
guard let data = data else { return }
do {
guard let resultArray = try JSONSerialization.jsonObject(with: data, options: []) as? [AnyObject] else { return }
for (key, result) in resultArray.enumerated() {
if let dictionary = result as? [String: AnyObject] {
let project = Project(id: key, dictionary: dictionary)
guard let imageUrl = project.imageUrl else { return }
self.fetchImage(withUrlString: imageUrl, completion: { (image) in
project.image = image
projectArray.append(project)
projectArray.sort(by: { (proje1, proje2) -> Bool in
return proje1.id! < proje2.id!
})
completion(projectArray)
})
}
}
} catch let error {
print("Failed to create json with error: ", error.localizedDescription)
}
}.resume()
}
private func fetchImage(withUrlString urlString: String, completion: @escaping(UIImage) -> ()) {
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("Failed to fetch image with error: ", error.localizedDescription)
return
}
guard let data = data else { return }
guard let image = UIImage(data: data) else { return }
completion(image)
}.resume()
}
}