Неустранимая ошибка: индекс выходит за пределы диапазона UITableView indexPath.row - PullRequest
0 голосов
/ 24 июня 2019

Ошибка индекса вне диапазона при попытке загрузить изображение с URL-адреса для indexPAth.row.

У меня есть правильная модель структуры для получения URL-адреса из ответа Json. И я могу получить URL в окне отладчика, но как только я пытаюсь получить изображение в cellForRowAt:, вот тогда я получаю ошибку Fata.

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return redditData.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "RedditTableCell", for: indexPath) as! RedditTableCell

        let post = redditData[indexPath.row]

        // uncomment this print statement and I get the fata error
        //print(post.data.preview?.images?[indexPath.row].source.url)   

        // uncomment this and in the debugger it will show the images URL path
        //print(post.data.preview?[0].source.url)  

        // each cell has only one   mainImage 
        print(post.data.preview?.images?[0].source?.url)  // prints the image url path, for each cell.
        cell.thumbnail.sd_setImage(with: URL(string: post.data.thumbnail!))
        cell.mainImage.sd_setImage(with: URL(string: (post.data.preview?.images?.source!.url)!)) 
        // images is an array [images]

        return cell
    }

Вот вывод отладчика:

https://www.reddit.com/r/all/.json
Optional("https://external-preview.redd.it/aF3ZkA26B3LsRG6ugjJTHAgn5uL_3y_iniPkFMGTZqY.jpg?auto=webp&s=1554c0af19a4e1776a29878c4c0c1cb1c1324c15")
Optional("https://preview.redd.it/cy8jp6qvvb631.jpg?auto=webp&s=cc5a0c15d130a4c54f33963ccce4cd1588871e85")
Optional("https://preview.redd.it/b39b3dgalb631.jpg?auto=webp&s=19b137dc245a243acda7c6a08b7d7e3d5b2acda6")
2019-06-24 13:37:46.137915-0500 MyRedditBrowser[15273:1933069] Task <77A8D26A-6460-48A2-9140-381470ABB7DF>.<1> finished with error - code: -1002
2019-06-24 13:37:46.140059-0500 MyRedditBrowser[15273:1933066] Task <77A8D26A-6460-48A2-9140-381470ABB7DF>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSErrorFailingURLStringKey=default, NSErrorFailingURLKey=default, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <77A8D26A-6460-48A2-9140-381470ABB7DF>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <77A8D26A-6460-48A2-9140-381470ABB7DF>.<1>, NSUnderlyingError=0x6000016d0600 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}} [-1002]

Так чего же супер базового мне не хватает? И иногда я вообще не вижу ни одного NSURLError ??

1 Ответ

0 голосов
/ 24 июня 2019

Вы говорите

print(post.data.preview?.images?[indexPath.row].source.url)

Если images пусто или его count меньше indexPath.row+1, вы потерпите крах.Поэтому заранее поставьте условие, чтобы проверить это.

if let count = post.data.preview?.images?.count, count > indexPath {
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...