如何在DetailViewController中获取JSONData?斯威夫特

时间:2019-07-04 08:28:59

标签: json swift api

我有2个控制器:CollectionViewControllerDetailViewController。在CollectionViewController中,我获取了数据并获得了coctails。现在,我要获取coctails?.drinks?[indexPath.row]并传递DetailViewController,在这里我需要再次fetchRequest,但是要使用另一个API和新的URL。但是在加载DetailViewController时,方法networkDataService.fetchDrink(drinkName: drinkName)不起作用。 我做错了什么?

struct Coctail: Codable {
   let drinks: [Drink]?
}

struct Drink: Codable {
   let strDrink : String?
   let strDrinkThumb : URL?
}

class NetworkDataService {

let networkManager = NetworkManager.shared

func fetchCoctails(completion: @escaping (Coctail?) -> Void) {
    let url = "https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Cocktail"
    networkManager.fetchData(url: url, completion: completion)
}

func fetchDrink(drinkName: String, completion: @escaping (Coctail?) -> Void) {
    let url = "https://www.thecocktaildb.com/api/json/v1/1/search.php?s=\(drinkName)"
    networkManager.fetchData(url: url, completion: completion)
   }
}

class CollectionViewController: UICollectionViewController {

var coctails: Coctail?
let networkDataService = NetworkDataService()

override func viewDidLoad() {
    super.viewDidLoad()

    networkDataService.fetchCoctails() { (coctails) in
        self.coctails = coctails

        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }
    }

}

// MARK: UICollectionViewDataSource

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return coctails?.drinks?.count ?? 0
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

    let drink = coctails?.drinks?[indexPath.row]

    cell.config(drink: drink)

    return cell
}

// MARK: - Navigation

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    guard let indexPath = collectionView.indexPathsForSelectedItems?.first else { return }
    let drink = coctails?.drinks?[indexPath.row]

    let destination = segue.destination as! DetailViewController
    destination.drinkName = drink?.strDrink ?? ""
   }
}

class DetailViewController: UIViewController {

var drinkName = ""
var coctail: Coctail?
let networkDataService = NetworkDataService()

override func viewDidLoad() {
    super.viewDidLoad()

    networkDataService.fetchDrink(drinkName: drinkName) { (coctail) in
        self.coctail = coctail
    }
}

1 个答案:

答案 0 :(得分:2)

如果您使用的饮料名称如strDrink中所示,则问题在于您发送的内容如下:

  

'57带白色车牌的雪佛兰

这意味着URL将类似于:

  

https://www.thecocktaildb.com/api/json/v1/1/search.php?s='57雪佛兰   带有白色车牌

并且不会自动转换为URL编码的URL。

此方法的问题在于,在将名称发送到API之前,您需要对其进行url编码。像这样:

networkDataService.fetchDrink(drinkName: drinkName.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)) { (coctail) in
    self.coctail = coctail
}

这样,您将获得带有以下内容的URL:

  

https://www.thecocktaildb.com/api/json/v1/1/search.php?s=%2757%20Chevy%20with%20a%20White%20License%20Plate

引用此URL编码的字符串: Swift - encode URL

另一方面,您的API返回饮料的ID idDrink,该ID应用于获取详细信息,而不是运行搜索,然后根据特定名称提取第一个。以后可能还会发生的事情是,您可能有两个具有不同值的杰克丹尼尔(Jack Daniel's),您将始终显示第一个。