gpt4 book ai didi

ios - 如何从api获取图片

转载 作者:行者123 更新时间:2023-11-28 23:36:55 24 4
gpt4 key购买 nike

我正在尝试从后端人员提供的 api 获取图像并下载图像,我正在通过 pods 使用“SDWebImage”。我的要求是:我将收集产品,在该集合数据中我有图像 url。我必须从该图像 url 获取该产品图像,我需要在单独的产品详细信息中显示该图像 Viewcontroller 但我遇到运行时错误,如“线程 1: fatal error :在展开可选值时意外发现 nil”。我在下面给出我的代码

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var imag: String = dict["photo"] as! String
lmpviewcontroller.userimgobj.sd_setImage(with: URL(string:imag), placeholderImage: UIImage(named: "Avatar-male.png"))
}

最佳答案

看到崩溃行会有所帮助,但您发布的代码中已经显示了一个潜力,您在其中强制解包了 JSON 中的字符串值:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
var imag: String = dict["photo"] as! String
lmpviewcontroller.userimgobj.sd_setImage(with: URL(string:imag), placeholderImage: UIImage(named: "Avatar-male.png"))
}

强制解包是使用 !

这应该是这样的:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
guard let imageURL: String = dict["photo"] as? String else { return }
lmpviewcontroller.userimgobj.sd_setImage(with: URL(string: imageURL), placeholderImage: UIImage(named: "Avatar-male.png"))
}

使用 force-unwrap 意味着您 100% 确定该值将始终存在。如果 id 不存在,那么您的应用程序将崩溃。

通过可选地检查它,您需要使用 if letguard let 检查它是否存在。一般来说,这类似于做:

let myOptionalValue: Any?
if myOptionalValue == nil {
return
} else {
doSomethingWithMyValue(myOptionalValue!)
}

但是 Swift 有更好的语法,如前所述。

关于ios - 如何从api获取图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54667876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com