如何在Swift中使用Ticketmaster API

huangapple go评论120阅读模式
英文:

How to use ticketmaster API in swift

问题

这是我第一次尝试使用API,我遇到了“keyNotFound”错误。有人能指导我更好地理解这个问题吗?这是他们文档的链接:https://developer.ticketmaster.com/products-and-docs/apis/discovery-api/v2/#anchor_find

  1. let apiKey = "************"
  2. struct EventResponse: Decodable {
  3. let events: [Event]
  4. }
  5. struct Event: Decodable {
  6. let id: String?
  7. }
  8. func fetchTMEvents() async throws -> [Event] {
  9. let urlTM = URL(string: "https://app.ticketmaster.com/discovery/v2/events.json?apikey=\(apiKey)")!
  10. let (data, _) = try await URLSession.shared.data(from: urlTM)
  11. let decoded = try JSONDecoder().decode(EventResponse.self, from: data)
  12. return decoded.events
  13. }
  1. Task {
  2. do {
  3. let events = try await fetchTMEvents()
  4. print("API results \(events)")
  5. } catch {
  6. print("API error \(error)")
  7. }
  8. }

完整错误信息:

keyNotFound(CodingKeys(stringValue: "events", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "events", intValue: nil) ("events").", underlyingError: nil))

英文:

This is the first time I have tried to use an API, I get the error "keyNotFound" Could someone point me in the right direction for understanding this better? Here is a link to their documentation: https://developer.ticketmaster.com/products-and-docs/apis/discovery-api/v2/#anchor_find

  1. let apiKey = "************"
  2. struct EventResponse : Decodable{
  3. let events : [Event]
  4. }
  5. struct Event : Decodable{
  6. let id : String?
  7. }
  8. func fetchTMEvents() async throws -> [Event]{
  9. let urlTM = URL(string: "https://app.ticketmaster.com/discovery/v2/events.json?apikey=\(apiKey)")!
  10. let(data, _) = try await URLSession.shared.data(from: urlTM)
  11. let decoded = try JSONDecoder().decode(EventResponse.self, from: data)
  12. return decoded.events
  13. }
  1. Task {
  2. do {
  3. let events = try await fetchTMEvents()
  4. print("API results \(events)")
  5. } catch {
  6. print("API error \(error)")
  7. }
  8. }

Full error:

> keyNotFound(CodingKeys(stringValue: "events", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "events", intValue: nil) ("events").", underlyingError: nil))

答案1

得分: 1

尝试使用这些测试模型来获取并解码events
在SwiftUI中的示例代码显示了如何显示结果。

注意,您必须有一个有效的apiKey,否则响应将无法解码。

要获取完整的结构模型集,请将JSON数据(所有数据)复制到
https://app.quicktype.io/ ,大部分代码会为您生成。 调整
代码
以满足您的需求。

您需要查阅文档以确定哪些结构/属性是可选的,
然后在它们后面添加?

  1. struct ContentView: View {
  2. @State var events: [Event] = []
  3. var body: some View {
  4. List(events) { event in
  5. Text(event.name)
  6. }
  7. .task {
  8. do {
  9. if let results = try await fetchTMEvents() {
  10. events = results
  11. }
  12. } catch {
  13. print("---> error: \(error)")
  14. }
  15. }
  16. }
  17. func fetchTMEvents() async throws -> [Event]? {
  18. let apiKey = "xxxxxxx"
  19. let urlTM = URL(string: "https://app.ticketmaster.com/discovery/v2/events.json?apikey=\(apiKey)")!
  20. let(data, _) = try await URLSession.shared.data(from: urlTM)
  21. // print(String(data: data, encoding: .utf8))
  22. let decoded = try JSONDecoder().decode(EventResponse.self, from: data)
  23. return decoded.embedded.events
  24. }
  25. }
  26. struct EventResponse: Codable {
  27. let embedded: ResponseEmbedded
  28. let page: Page
  29. enum CodingKeys: String, CodingKey {
  30. case page
  31. case embedded = "_embedded"
  32. }
  33. }
  34. struct ResponseEmbedded: Codable {
  35. let events: [Event]?
  36. }
  37. struct Event: Codable, Identifiable {
  38. let name, type, id, url, locale: String
  39. }
  40. struct Page: Codable {
  41. let size, totalElements, totalPages, number: Int
  42. }

Hope this helps!

英文:

Try these test models to fetch then decode the events.
The example code in SwiftUI shows how to display the results.

Note, you must have a valid apiKey otherwise the response will not be decodable.

To get the full set of struct models, just copy the json data (all of it) to
https://app.quicktype.io/ and the bulk of the code is generated for you. Adjust that
code
to suit your needs.

You will have to consult the docs to determine which struct/properties are optional,
then add ? to them.

  1. struct ContentView: View {
  2. @State var events: [Event] = []
  3. var body: some View {
  4. List(events) { event in
  5. Text(event.name)
  6. }
  7. .task {
  8. do {
  9. if let results = try await fetchTMEvents() {
  10. events = results
  11. }
  12. } catch {
  13. print("---> error: \(error)")
  14. }
  15. }
  16. }
  17. func fetchTMEvents() async throws -> [Event]? {
  18. let apiKey = "xxxxxxx"
  19. let urlTM = URL(string: "https://app.ticketmaster.com/discovery/v2/events.json?apikey=\(apiKey)")!
  20. let(data, _) = try await URLSession.shared.data(from: urlTM)
  21. // print(String(data: data, encoding: .utf8))
  22. let decoded = try JSONDecoder().decode(EventResponse.self, from: data)
  23. return decoded.embedded.events
  24. }
  25. }
  26. struct EventResponse: Codable {
  27. let embedded: ResponseEmbedded
  28. let page: Page
  29. enum CodingKeys: String, CodingKey {
  30. case page
  31. case embedded = "_embedded"
  32. }
  33. }
  34. struct ResponseEmbedded: Codable {
  35. let events: [Event]?
  36. }
  37. struct Event: Codable, Identifiable {
  38. let name, type, id, url, locale: String
  39. }
  40. struct Page: Codable {
  41. let size, totalElements, totalPages, number: Int
  42. }

huangapple
  • 本文由 发表于 2023年7月17日 09:04:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76700982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定