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()
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With