当尝试从indexPAth.row的URL加载图像时,出现索引超出范围错误。
我具有正确的结构模型,可以从Json响应中获取URL。而且我可以在调试器窗口中获取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?
答案 0 :(得分:0)
您在说
print(post.data.preview?.images?[indexPath.row].source.url)
如果images
为空或其count
小于indexPath.row+1
,则会崩溃。因此,请事先做好条件检查。
if let count = post.data.preview?.images?.count, count > indexPath {