如何在Swift中使用Ticketmaster API

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

How to use ticketmaster API in swift

问题

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

let apiKey = "************"

struct EventResponse: Decodable {
    let events: [Event]
}

struct Event: Decodable {
    let id: String?
}

func fetchTMEvents() async throws -> [Event] {
    let urlTM = URL(string: "https://app.ticketmaster.com/discovery/v2/events.json?apikey=\(apiKey)")!
    let (data, _) = try await URLSession.shared.data(from: urlTM)
    let decoded = try JSONDecoder().decode(EventResponse.self, from: data)
    return decoded.events
}
Task {
    do {
        let events = try await fetchTMEvents()
        print("API results \(events)")
    } catch {
        print("API error \(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))

英文:

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

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

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/ ,大部分代码会为您生成。 调整
代码
以满足您的需求。

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

struct ContentView: View {
    @State var events: [Event] = []
    
    var body: some View {
        List(events) { event in
            Text(event.name)
        }
        .task {
            do {
                if let results = try await fetchTMEvents() {
                    events = results
                }
            } catch {
                print("---> error: \(error)")
            }
        }
    }
    
    func fetchTMEvents() async throws -> [Event]? {
        let apiKey = "xxxxxxx"
        let urlTM = URL(string: "https://app.ticketmaster.com/discovery/v2/events.json?apikey=\(apiKey)")!
        let(data, _) = try await URLSession.shared.data(from: urlTM)
        // print(String(data: data, encoding: .utf8))
        let decoded = try JSONDecoder().decode(EventResponse.self, from: data)
        return decoded.embedded.events
    }
}

struct EventResponse: Codable {
    let embedded: ResponseEmbedded
    let page: Page

    enum CodingKeys: String, CodingKey {
        case page
        case embedded = "_embedded"
    }
}

struct ResponseEmbedded: Codable {
    let events: [Event]?
}

struct Event: Codable, Identifiable {
    let name, type, id, url, locale: String
}

struct Page: Codable {
    let size, totalElements, totalPages, number: Int
}

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.

struct ContentView: View {
    @State var events: [Event] = []
    
    var body: some View {
        List(events) { event in
            Text(event.name)
        }
        .task {
            do {
                if let results = try await fetchTMEvents() {
                    events = results
                }
            } catch {
                print("---> error: \(error)")
            }
        }
    }
    
    func fetchTMEvents() async throws -> [Event]? {
        let apiKey = "xxxxxxx"
        let urlTM = URL(string: "https://app.ticketmaster.com/discovery/v2/events.json?apikey=\(apiKey)")!
        let(data, _) = try await URLSession.shared.data(from: urlTM)
        // print(String(data: data, encoding: .utf8))
        let decoded = try JSONDecoder().decode(EventResponse.self, from: data)
        return decoded.embedded.events
    }
}

struct EventResponse: Codable {
    let embedded: ResponseEmbedded
    let page: Page

    enum CodingKeys: String, CodingKey {
        case page
        case embedded = "_embedded"
    }
}

struct ResponseEmbedded: Codable {
    let events: [Event]?
}

struct Event: Codable, Identifiable {
    let name, type, id, url, locale: String
}

struct Page: Codable {
    let size, totalElements, totalPages, number: Int
}

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:

确定