我目前正在构建一个应用程序,以显示推特列表中的推文。出于某种原因,我只在推文中添加媒体链接,跳过只有全文而没有媒体的推文。JSON数据打印我请求的所有推文。有人知道如何调整我的case let声明,这样我就可以在没有媒体的情况下包含推文吗?
**以下是我如何设置结构:**
struct TweetData: Codable, Identifiable {
var id: String { id_str }
var id_str: String
var full_text: String?
var screen_name: String?
var name: String?
var profile_image_url_https: String?
var media_url_https: String?
}
**以下是我为twitter列表编码函数的方式:**
func listTweets(listTag: ListTag) {
swifter.listTweets(for: ListTag.id("1580201555286192128"), count: 20, includeEntities: true, includeRTs: true, tweetMode: .extended) { JSON in
do {
switch JSON {
case .array(let array):
var tweets: [TweetData] = []
for json in array {
if case let .string(id) = json["id_str"],
case let .string(full_text) = json["full_text"],
case let .string(screen_name) = json["user"]["screen_name"],
case let .string(name) = json["user"]["name"],
case let .string(profile_image_url_https) = json["user"]["profile_image_url_https"],
case let .string(media_url_https) = json["entities"]["media"][0]["media_url_https"] {
tweets.append(TweetData(id_str: id, full_text: full_text, screen_name: screen_name, name: name, profile_image_url_https: profile_image_url_https, media_url_https: media_url_https))
}
}
DispatchQueue.main.async { self.fantasyNews = tweets }
default:
print("Can't handle object: (JSON)")
}
} catch {
print("Got an error while parsing tweets: (error)")
}
}
**在我的内容视图中,以下是我对推特的称呼:**
Text(tweet.full_text!)
AsyncImage(url: URL(string: tweet.media_url_https!)!,
placeholder: { Text("Loading ...") },
image: { Image(uiImage: $0).resizable() })
.aspectRatio(contentMode: .fit)
.onAppear() {
networkManager.listTweets(listTag: .id("1580201555286192128"))
}
在Swifter上读取ReadMe文件后,我发现我的case let语句的语法不正确。.string必须遵循常量的定义。此外,在第一个语句中需要一个零合并运算符。
for json in array {
if case let id = json["id_str"].string ?? "",
case let full_text = json["full_text"].string,
case let screen_name = json["user"]["screen_name"].string,
case let name = json["user"]["name"].string,
case let profile_image_url_https = json["user"]["profile_image_url_https"].string,
case let media_url_https = json["entities"]["media"][0]["media_url_https"].string {
tweets.append(TweetData(id_str: id, full_text: full_text, screen_name: screen_name, name: name, profile_image_url_https: profile_image_url_https, expanded_url: expanded_url, media_url_https: media_url_https))
}
现在,在我使用AsyncImage的内容视图中,我必须调用一个可选的语句,即如果没有媒体URL链接,那么将发布一个白色像素。我不知道如何绕过这一部分,但它起了作用,这就是它看起来的样子。
AsyncImage(url: (URL(string: tweet.media_url_https ?? "https://commons.wikimedia.org/wiki/File:1x1_placeholder.png#/media/File:1x1_placeholder.png"))!,
placeholder: { Text("") },
image: { Image(uiImage: $0).resizable() })
.aspectRatio(contentMode: .fit)