显示图片时出现IOS Swift超出范围错误
我有来自Json的数据,并将其填充到TableView中。我从Json中得到的其中一个元素是一个字符串,它有一个指向图像的URL。如果某个特定的Json字符串为null或空白,则会出现以下错误显示图片时出现IOS Swift超出范围错误,ios,swift,uitableview,swift3,Ios,Swift,Uitableview,Swift3,我有来自Json的数据,并将其填充到TableView中。我从Json中得到的其中一个元素是一个字符串,它有一个指向图像的URL。如果某个特定的Json字符串为null或空白,则会出现以下错误 fatal error: Index out of range 每个帖子都不会有图像,但如果字符串为空,我不知道如何告诉swift忽略某段代码。这是我的密码 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPat
fatal error: Index out of range
每个帖子都不会有图像,但如果字符串为空,我不知道如何告诉swift忽略某段代码。这是我的密码
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomePageTVC", for: indexPath) as! HomePageTVC
cell.post.text = Posts[indexPath.row]
// Start Display Image
// right here I get the fatal out of index if there is no image
if profile_image_string[indexPath.row] != nil {
let imgURL: NSURL = NSURL(string: profile_image_string[indexPath.row])!
let request:NSURLRequest = NSURLRequest(url: imgURL as URL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
DispatchQueue.main.async(execute: { () -> Void in
if data != nil {
cell.profile_image.image = UIImage(data: data!)
}
})
});
task.resume()
}
// End Display Image
return cell
}
这是正在返回的Json
{"post":"Check check","profile_image":null},
{"post":"check check","profile_image":"http://www.myurl.com/cats.jpg}
请注意,如果不存在图像url,则默认值为null。我如何在TableView代码中检查它?因为我确信正在发生的事情是,它获取空值并试图将其转换为图像,因此我得到了错误。字符串URL的值保存在此字符串数组中
profile_image_string[indexPath.row]
这就是我附加它的方式
if let profile_picture = Stream["profile_image"] as? String {
self.profile_image_string.append(profile_picture)
}
不管怎样,正如前面所说,我正在成功地从Json获取URL字符串,如果它是URL,那么图像显示,我只想知道如何检查空值,这样我就不会得到错误。任何帮助都是非常好的。这部分是非常错误的
if let profile_picture = Stream["profile_image"] as? String {
self.profile_image_string.append(profile_picture)
}
如果您想要一致的数组值,您必须通过使其类型
[string?]
使您的profile\u image\u string
可以包含nil
,如果如果let
失败,则将nil
值附加到数组中,如下所示:
if let....else {
self.profile_image_string.append(nil)
}
不过,这种方法非常混乱,不建议使用,我建议您创建适当的对象来保存JSON数据
profile\u image\u字符串
的元素小于indexPath.row
。检查您从numberOfRows
method返回的号码感谢您现在就这么做