Массив объявлений в табличном представлении вне индекса

#arrays #swift #uitableview #admob #ads

#массивы #быстрый #uitableview #admob #реклама

Вопрос:

У меня есть 3 массива данных. Я хочу показывать рекламу после каждых 5 пользовательских ячеек в таблице.

 var nativeAds = [GADNativeAd]() var item = [NewsElement]() var filterItem = [NewsElement]()  

После отображения 5 ячеек с объявлениями приложение завершает работу с ошибкой «Поток 1: Фатальная ошибка: Индекс вне диапазона».

Как мне повторно добавить объявления в массив или снова выбрать массив с объявлениями? Здесь сидят умные ребята, пожалуйста, помогите мне. Заранее благодарю вас!

ниже приведен мой код

 extension NewsViewController: GADNativeAdLoaderDelegate {  func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) {  print("(adLoader) failed with error: (error.localizedDescription)")  }    func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {  print("Received native ad: (nativeAd)")  nativeAds.append(nativeAd)  }    func adLoaderDidFinishLoading(_ adLoader: GADAdLoader) {  newsTblView.reloadData()  } }  
 extension NewsViewController: UITableViewDelegate, UITableViewDataSource {    private func dataRow(for indexPath: IndexPath) -gt; Int? {  let (quotient, remainder) = (indexPath.row   1).quotientAndRemainder(dividingBy: numAdsToLoad)  if remainder == 0 { return nil }  return quotient * (numAdsToLoad - 1)   remainder - 1  }    private func adRow(for indexPath: IndexPath) -gt; Int? {  let (quotient, remainder) = (indexPath.row   1).quotientAndRemainder(dividingBy: numAdsToLoad)  if remainder != 0 { return nil }  return quotient - 1  }    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -gt; Int {  if searchActive {  return filterItem.count  } else {  return item.count   nativeAds.count  }  }    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -gt; UITableViewCell {  if let row = dataRow(for: indexPath) {  let cell = tableView.dequeueReusableCell(withIdentifier: "NewsTableViewCell", for: indexPath) as! NewsTableViewCell  if searchActive {  let items = filterItem[row]  cell.configCell(model: items )  } else {  let items = item[row]  cell.configCell(model: items )  }  cell.selectionStyle = .none  cell.backgroundColor = .clear  return cell  } else if let row = adRow(for: indexPath) {  let nativeAd = nativeAds[row] lt;-- "Thread 1: Fatal error: Index out of range"  nativeAd.rootViewController = self  let nativeAdCell = tableView.dequeueReusableCell(withIdentifier: "UnifiedNativeAdCell", for: indexPath) as! GADNativeAdViewCell  nativeAdCell.setAdData()  return nativeAdCell  }  fatalError("Did not find data or ad for cell: Should never get here")  } }  

Комментарии:

1. Это выглядит очень хрупким, и математике, которую вы используете, нелегко следовать, так как существует так много неизвестных. например, что такое numAdsToLoad и сколько элементов у вас в массиве nativeAds, он постоянный или как-то меняется?

2. numAdsToLoad = 5. Массив nativeAds является постоянным.

3. Итак, если у вас есть 10 товаров, то будет показано 2 объявления, верно? Но TableView(numberOfRowsInSection:) вернет 15, а не 12.

4. Нет, мой массив заполняет 50 ячеек, а объявление заполняет 5 ячеек, когда в моей таблице должно отображаться 6 ячеек с объявлением, приложение выходит из строя. Мне нужно повторно выбрать массив с рекламой или повторно добавить рекламу в массив

5. Как я уже сказал, здесь так много информации отсутствует, так что помочь очень трудно.