[英]How to display image from url in swift
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.我正在进行一个异步调用,其中 JSON 响应包含我想在 UIImageView 中显示的图像的文本和 url。 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)
}
导入并使用翠鸟
self.imageview.kf.setImage(with: "url")
yourImage.sd_setImage(with: URL(string: yourImageUrl)) yourImage.sd_setImage(with: URL(string: yourImageUrl))
//and if you want to put image on your cell //如果你想把图像放在你的单元格上
cell.imageView.sd_setImage(with: URL(string: userModel[indexPath.row].url)) cell.imageView.sd_setImage(with: URL(string: userModel[indexPath.row].url))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.