4

I'm making an async call which the JSON response contains both text and url to images that I want to display in a UIImageView. Now displaying the text in a label isn't the problem but loading the images is giving me hard times. Have shared my code below.

//Declared variables to hold response
    var offerContent: String?
    var offerImage: URL?
    var offerTitle: String?
    var suggestionLabel:String?
    var suggestionScreen: String?



//create a task to send reques
            let task = URLSession.shared.dataTask(with: request as URLRequest){
                data, response, error in
                if error != nil {
                    print("error is:: \(error!.localizedDescription)")
                    return;
                }
                //parsing the response
                do {
                    // converting response to NSDictionary
                    let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    DispatchQueue.main.async {
                        if let parseJSON = myJSON{
                            var responseCode: Int!
                            var responseMessage: NSArray!

                            //getting the json response
                            responseCode = parseJSON["RESPONSECODE"] as! Int?
                            responseMessage = parseJSON["RESPONSEMESSAGE"] as! NSArray?

                            if responseCode == 0 {
                                for obj in responseMessage{
                                    if let dict = obj as? NSDictionary{
                                        self.offerContent = dict.value(forKey: "CONTENT") as? String
                                        self.offerTitle = dict.value(forKey: "TITLE") as? String
                                        self.suggestionLabel = dict.value(forKey: "SUGGESTION_LABEL") as? String
                                        self.suggestionScreen = dict.value(forKey: "SUGGESTION_SCREEN") as? String
                                        self.offerImage = dict.value(forKey: "IMAGE") as? URL
//                                        print("image:: \(self.offerImage!)")

                                        let offerImageView = UIImageView()
                                        self.darkView.addSubview(offerImageView)
                                        offerImageView.heightAnchor.constraint(equalToConstant: 30).isActive = true
                                        offerImageView.widthAnchor.constraint(equalTo: self.darkView.widthAnchor).isActive = true
                                        offerImageView.topAnchor.constraint(equalTo: self.darkView.topAnchor, constant: 20).isActive = true
                                        offerImageView.image = UIImage(data: self.offerImage)
                                    }
                                }
                            }

                            print(parseJSON)
                        }
                        }
                }catch{
                    print("catch:: \(error.localizedDescription)")
                }

            }
            task.resume()
chevi99
  • 123
  • 1
  • 2
  • 17
  • Is your `dict.value(forKey: "IMAGE")` content an url ? – GIJOW Aug 14 '18 at 16:17
  • you can use sdwebimage for displaying image url – Muhammed Azharudheen Aug 14 '18 at 16:31
  • @GIJOW yes it contains url. So i have edited my codes to make it url – chevi99 Aug 14 '18 at 16:31
  • 1
    Possible duplicate of [Loading/Downloading image from URL on Swift](https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift) – GIJOW Aug 14 '18 at 16:33
  • You can refer to this post: https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift also, you're handling your url as data (binary data) `UIImage(data: self.offerImage)`. It will never work. – GIJOW Aug 14 '18 at 16:34
  • Thanks @MuhammedAzharudheen i imported sdwebimage and its working fine. – chevi99 Aug 16 '18 at 12:21

2 Answers2

12

Try this code.

let url = URL(string: "IMAGE URL HERE")
let data = try? Data(contentsOf: url)

if let imageData = data {
    let image = UIImage(data: imageData)
}
Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
Keyur Faldu
  • 195
  • 9
-1

Import and use Kingfisher

self.imageview.kf.setImage(with: "url")