Swathi
Swathi

Reputation: 31

how to get image from api

I am trying to get image from api which is given by backend people and to download the images,i am using "SDWebImage" through pods.My requirement is: i will be having a collection of products,in that collection data i have image url.i have to get that product image from that image url and i need to show that image in separate product details Viewcontroller But i am getting a run time error like "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"..I am giving my code below

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"))
}

Upvotes: 0

Views: 210

Answers (3)

Sukh
Sukh

Reputation: 1398

//with sd image

  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")
                    }
    }

Upvotes: 0

Ahmed Abdallah
Ahmed Abdallah

Reputation: 2355

I suggest using Kingfisher

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
      if let  imag = dict["photo"]{
      let url = URL(string: imag)
      userimgobj.kf.setImage(with: url)
      }
}

Upvotes: 0

Matic Oblak
Matic Oblak

Reputation: 16794

It would help to see the crashing line but already a potential is shown in the code you posted where you force-unwrap a string value from 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"))
}

The force-unwrapping is with using !.

This should be something like:

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"))
}

By using force-unwrap it means you are 100% sure that this value will always exist. And if id does not then your application will crash.

By checking it optionally you need to check for it existence with either if let or guard let. In general this is similar to doing:

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

but Swift has nicer syntax as displayed previously.

Upvotes: 1

Related Questions