[英]how to get an image with specific id from Facebook graph api iOS?
[英]how to get image from api
我正在尝试从后端人员提供的api获取图像并下载图像,我通过pods使用“ SDWebImage
”。我的要求是:我将要收集产品,因为该收集数据中包含图像url .i必须从该图像URL中获取该产品图像,并且需要在单独的产品详细信息中显示该图像Viewcontroller
但是我遇到了运行时错误,例如“线程1:致命错误:在展开可选值时意外发现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"))
}
通过使用强制展开,这意味着您100%确保该值将始终存在。 如果没有id,则您的应用程序将崩溃。
通过可选地检查它,您需要使用if let
或guard let
检查它的存在。 通常,这类似于:
let myOptionalValue: Any?
if myOptionalValue == nil {
return
} else {
doSomethingWithMyValue(myOptionalValue!)
}
但是Swift的语法更好,如先前所示。
我建议使用翠鸟
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let imag = dict["photo"]{
let url = URL(string: imag)
userimgobj.kf.setImage(with: url)
}
}
//带有SD图像
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if dict["photo"] != nil{
lmpviewcontroller.userimgobj.sd_setImage(with: URL(string:imag)), completed: nil)
}else{
lmpviewcontroller.userimgobj = UIImage(named: "placeholder")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.