gpt4 book ai didi

ios - 如何在swift中显示来自url的图像

转载 作者:搜寻专家 更新时间:2023-11-01 06:00:45 24 4
gpt4 key购买 nike

我正在进行一个异步调用,其中 JSON 响应包含我想在 UIImageView 中显示的图像的文本和 url。现在在标签中显示文本不是问题,但加载图像让我很难受。在下面分享了我的代码。

//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()

最佳答案

试试这段代码。

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

if let imageData = data {
let image = UIImage(data: imageData)
}

关于ios - 如何在swift中显示来自url的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51845767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com