使用Alamofire在Swift 4中解析Youtube api

问题描述 投票:0回答:1

我试图解析Youtube api在Swift 4中使用Alamofire到目前为止我确实得到了结果并且一切正常,但是我无法访问“项目”

所以基本上我想访问标题,描述,中等缩略图url和resultsPerPage。

我尝试了很多解决方案,但是如果然后非工作,特别是我使用Swift 4和Alamofire

JSON:

{  
   "kind":"youtube#searchListResponse",
   "etag":"\"XI7nbFXulYBIpL0ayR_gDh3eu1k/N6oV8CScLhAtqc_fDnA3Nw4U3RA\"",
   "nextPageToken":"CBkQAA",
   "regionCode":"US",
   "pageInfo":{  
      "totalResults":922098,
      "resultsPerPage":25
   },
   "items":[  
      {  
         "kind":"youtube#searchResult",
         "etag":"\"XI7nbFXulYBIpL0ayR_gDh3eu1k/Oxu5v7t2PHcDK4wvSo-xsIp3Raw\"",
         "id":{  },
         "snippet":{  
            "publishedAt":"2011-03-21T08:32:25.000Z",
            "channelId":"UC1r4VtVE__5K6c_L_3Vlxxg",
            "title":"fouseyTUBE",
            "description":"",
            "thumbnails":{  
               "default":{  
                  "url":"https://yt3.ggpht.com/-oBs78-0JLws/AAAAAAAAAAI/AAAAAAAAAAA/zKWHSghRD3U/s88-c-k-no-mo-rj-c0xffffff/photo.jpg"
               },
               "medium":{  
                  "url":"https://yt3.ggpht.com/-oBs78-0JLws/AAAAAAAAAAI/AAAAAAAAAAA/zKWHSghRD3U/s240-c-k-no-mo-rj-c0xffffff/photo.jpg"
               },
               "high":{  
                  "url":"https://yt3.ggpht.com/-oBs78-0JLws/AAAAAAAAAAI/AAAAAAAAAAA/zKWHSghRD3U/s800-c-k-no-mo-rj-c0xffffff/photo.jpg"
               }
            },
            "channelTitle":"fouseyTUBE",
            "liveBroadcastContent":"none"
         }
      }
]
}

我的代码:

let url = "https://www.googleapis.com/youtube/v3/search"
        let parameters = ["q": searchText, "maxResults": 25, "part": "snippet", "type":"video", "key": "MY_YOUTUBE_API_KEY"] as [String : Any]

        Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseData { (dataResponse) in
            if let err = dataResponse.error {
                print("Failed to contact server", err)
                return
            }

            guard let data = dataResponse.data else {return}
            do{
                let searchResult = try
                    JSONDecoder().decode(SearchResults.self, from: data)
                print("Results Count:", searchResult.kind)
                searchResult.items.forEach({ (data) in

                    print(searchResult.items["data"]["items"])
                })
                self.musics = searchResult.items
                self.tableView.reloadData()

            }catch let decodeErr {
                print("Failed to Descode: ", decodeErr)
            }


        }
    }

    struct SearchResults: Decodable{
        let kind: String
        let items: [Music]
    }

Music.Swift文件

struct Music: Decodable {
    var etag: String?
    var kind: String?
    //let time: String
}
ios json swift swift4 alamofire
1个回答
2
投票

我建议为每个嵌套元素创建可解码的结构,如下所示,

struct PageInfo: Decodable {
    var totalResults = 0
    var resultsPerPage = 0
}


struct Snippet: Decodable {
    var channelId = ""
    var title = ""
    var description = ""
    var channelTitle = ""
    var thumbnails: Thumbnail
}


struct ChannelURL: Decodable {
    var url = ""
}

struct Thumbnail: Decodable {
    var medium: ChannelURL
    var high: ChannelURL
}

struct Item: Decodable {
    var kind = ""
    var etag = ""
    var snippet: Snippet

}


struct Result: Decodable {
    var kind = ""
    var etag = ""
    var pageInfo: PageInfo
    var items: [Item]
}

然后继续解码。以下解码适用于您的上述响应。

    do {


        let decoded = try JSONDecoder().decode(Result.self, from: data)
        debugPrint(decoded)


        //Now access the data
        print(decoded.pageInfo.resultsPerPage) // 25

        //since the items is array we take first for now
        if  let firstItem = decoded.items.first {
            //to print the first one
            print(firstItem.snippet.channelTitle) // "fouseyTUBE"

            //same for URL
            print(firstItem.snippet.thumbnails.medium.url) // https://yt3.ggpht.com/-oBs78-0JLws/AAAAAAAAAAI/AAAAAAAAAAA/zKWHSghRD3U/s240-c-k-no-mo-rj-c0xffffff/photo.jpg
        }


    } catch {
        debugPrint("\(error.localizedDescription)")
    }

这是所有数据都存在的最佳情况。所以你必须相应地修改你的结构,使得一些值为``

© www.soinside.com 2019 - 2024. All rights reserved.