使用 Swift 解析来自 GIPHY API 的 JSON 信息

Parsing JSON information from GIPHY API with Swift

提问人:Dylan 提问时间:6/8/2022 更新时间:6/8/2022 访问量:191

问:

我目前正在尝试创建一个在表格视图中显示趋势 gif 的 iOS 应用程序,我一直在疯狂地尝试从 GIPHY API 访问图像 URL。我目前正在使用 alamo fire 来访问数据,这就是我的代码到目前为止的样子。

import UIKit
import Alamofire

class ViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        fetchGiphyData()

    }
    
    func fetchGiphyData() {
    
        let request = AF.request("https://api.giphy.com/v1/gifs/trending?api_key=zONZGFIbbvYDBjLEBlgKxLjbsClfmptw&limit=25&rating=pg-13")
        
        request.responseDecodable(of: GiphyData.self) { (response) in
            guard let gifs = response.value else { return }
            print(gifs.height)
            
        }
    }
}

这就是我为 JSON 信息设置数据收集的方式。

import UIKit

struct Data: Codable {
    var data: [ImageInfo]
}

struct ImageInfo: Codable {
    var images: ImageTypes
}

struct ImageTypes: Codable {
    var original: GiphyData
}

struct GiphyData: Codable {
    var url: String
    var height: String
}

struct GiphyImages: Codable {
    var giphyImages: [GiphyData]
}

这是来自 GIPHY 的 API 信息

{
"data":[
{
"type":"gif"
"id":"If1a3H7OHi8vmiCTpW"
"url":"https://giphy.com/gifs/nhl-draft-nhl-2019-prospects-If1a3H7OHi8vmiCTpW"
"slug":"nhl-draft-nhl-2019-prospects-If1a3H7OHi8vmiCTpW"
"bitly_gif_url":"https://gph.is/g/Zdx6J5o"
"bitly_url":"https://gph.is/g/Zdx6J5o"
"embed_url":"https://giphy.com/embed/If1a3H7OHi8vmiCTpW"
"username":"nhl"
"source":""
"title":"Ice Hockey Sport GIF by NHL"
"rating":"g"
"content_url":""
"source_tld":""
"source_post_url":""
"is_sticker":0
"import_datetime":"2019-07-03 17:13:37"
"trending_datetime":"2022-06-04 03:31:37"
"images":{
"original":{
"height":"500"
"width":"500"
"size":"3765578"
"url":"https://media3.giphy.com/media/If1a3H7OHi8vmiCTpW/giphy.gif?cid=84449cd9g1p95f9hyvvtbnajoj9j2ma4tnrpfcurbplr6brq&rid=giphy.gif&ct=g"

我只是想在原始目录下获取网址,以便我可以在表格视图中显示图像。有谁知道为什么我无法访问网址?

iOS JSON Swift API 解析

评论

0赞 Larme 6/8/2022
不相关,但不要命名您的自定义结构/类,因为它已经存在于 Swift 中,因此您可能需要每次都去掩饰(这很痛苦)......你写了,但你的回答是 ,而不是 ,你应该有错误,不是吗?DataresponseDecodable(of: GiphyData.self)DataGiphyData
0赞 Faran Rasheed 6/8/2022
尝试将 Data Struct 重命名为 GiphyResponseData 等其他名称,然后将其替换为 GiphyResponseData,而不是解析对 GiphyData 的响应。如下。request.responseDecodable(的: GiphyResponseData.self)
0赞 Dylan 6/8/2022
@FaranRasheed我试图将数据放入结构 GiphyImages 中以创建 url 数组,但我不确定这是否正确
0赞 Dylan 6/8/2022
@FaranRasheed 这确实奏效了!我将数据结构更新为 GiphyReponseData,现在正在解析该结构。现在我只需要将所有这些 url 上传到表视图中
0赞 Faran Rasheed 6/8/2022
很乐意帮忙。请为我的评论投赞成票,以便其他人可以从中受益。

答: 暂无答案