gpt4 book ai didi

ios - 可选类型的默认值 'URL?'

转载 作者:行者123 更新时间:2023-11-30 10:26:16 26 4
gpt4 key购买 nike

我有一个扩展程序,允许我从 API 将图像下载到我的 UITableView

extension UIImageView {

func donwloadImage(from url: String) {
let urlRequest = URLRequest(url: URL(string: url)!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

if error != nil {
print(error)
return
}

DispatchQueue.main.async {
self.image = UIImage(data: data!)

}
}
task.resume()
}

}

如果 imageUrlnil,应用程序就会崩溃。

如何使用 ?? 包装它,这样如果没有图像,UIImageView 就只是空白?

这是一个数据模型和获取数据函数

class Article: NSObject {

var headline: String?
var date: String?
var imageUrl: String?
var desc: String?
var url: String?

}

@objc func fetchArticles() {
let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v2/everything?pageSize=15&sortBy=publishedAt&apiKey=API_KEY")!)

let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

if error != nil {
print(error)
return
}

self.articles = [Article]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]

if let articlesFromJson = json["articles"] as? [[String: AnyObject]] {
for articlesFromJson in articlesFromJson {
let article = Article()
if
let title = articlesFromJson["title"] as? String,
let publishedAt = articlesFromJson["publishedAt"] as? String,
let urlToImage = articlesFromJson["urlToImage"] as? String,
let description = articlesFromJson["description"] as? String,
let url = articlesFromJson["url"] as? String

{

article.headline = title
article.date = publishedAt
article.imageUrl = urlToImage
article.desc = description
article.url = url


}
self.articles?.append(article) // and so on...

最佳答案

我建议您使用异步下载图像并始终留下 placeHolder 图像的 POD,请看以下使用它的示例:

import SDWebImage

imageView.sd_setImage (
with: URL (string: "http://www.example.com/image.jpg"),
placeholderImage: UIImage (named: "placeholder.png") // define your default Image
)

POD 链接:https://cocoapods.org/pods/SDWebImage

希望这有帮助。

关于ios - 可选类型的默认值 'URL?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60030025/

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