如何在Swift中使用单一模型显示不同形式的数据

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

How to display different form of data with single Model in swift

问题

以下是您要翻译的代码部分:

func getUsers(completion: @escaping (Result<[ResultItem], NetworkError>) -> ()) {
    var uri = ""
    if (withID != ""){
      uri = "/test/withID"
    }
    else {
        uri = "/test"
    }
    let method = GET
    let urlString = "https:myownURL\(uri)"
    //生成标头
    let urlHeader = headersGenerator()
    URLSession.shared.dataTask(with: urlHeader) { [self] (data, response , error) in
        guard let data = data else { return }
        print(String(data: data, encoding: .utf8) ?? "Invalid JSON")
        do {
           let results = try JSONDecoder().decode(Results.self, from: data)
           completion(.success(results.userInfo))
        } catch {
           print("Error:\(error)")
        }
    }.resume()
}
struct Results: Codable {
    let userInfo: [ResultItem]
}

struct ResultItem: Codable, Identifiable {
    let id = UUID()
    let userId: String
    var userlastname: String
    var username: String
}

这是代码的翻译部分,没有其他内容。

英文:

I am having a function for api request as below

  func getUsers(completion:@escaping (Result&lt;[ResultItem],NetworkError&gt;) -&gt; ()) {
        var uri = &quot;&quot;;
        if(withID != &quot;&quot;){
          uri = &quot;\test\withID&quot;
        }

        
        else {
            uri = &quot;\test&quot;
        }
        
        let method = GET
        let urlString = &quot;https:myownURL\(uri)&quot;
        
//generates a header
        let urlHeader=headersGenerator()

        URLSession.shared.dataTask(with: urlHeader) { [self] (data, response , error) in
            guard let data = data else { return }
            print(String(data: data, encoding: .utf8) ?? &quot;Invalid JSON&quot;)

            do {
               let results = try JSONDecoder().decode(Results.self,from: data)
           
             completion(.success(results.userInfo))
            } catch {
             print(&quot;Error:\(error)&quot;)
          

            }
        }.resume()
    }

Model is as follows

struct Results: Codable {
    let userInfo:[ResultItem]
}

struct ResultItem: Codable, Identifiable {
    let id = UUID()
    let userId: String
    var userlastname:String
    var username:String
}

This is giving me a proper response as below when I dont pass withID(the url will be https:myownURL.test )

The output is as below

{&quot;userInfo&quot;:[{&quot;userId&quot;:&quot;0390&quot;,&quot;userlastname&quot;:&quot;test1&quot;,&quot;username&quot;:&quot;test1&quot;},{&quot;userId&quot;:&quot;0391&quot;,&quot;userlastname&quot;:&quot;test2&quot;,&quot;username&quot;:&quot;test2&quot;},{&quot;userId&quot;:&quot;0392&quot;,&quot;userlastname&quot;:&quot;test3&quot;,&quot;username&quot;:&quot;test3&quot;}]}

But if i run the url with withID(the url will be https:myownURL.test.withID )
the output should give single value, and I am getting a single value but the format if different

{&quot;userId&quot;:&quot;0390&quot;,&quot;userlastname&quot;:&quot;test1&quot;,&quot;username&quot;:&quot;test1&quot;}

but the model is same for both API so that it should return response as below

{&quot;userInfo&quot;:[{&quot;userId&quot;:&quot;0390&quot;,&quot;userlastname&quot;:&quot;test1&quot;,&quot;username&quot;:&quot;test1&quot;}]}

please let me know what mistake I am doing so that the response will come like this

{&quot;userInfo&quot;:[{&quot;userId&quot;:&quot;0390&quot;,&quot;userlastname&quot;:&quot;test1&quot;,&quot;username&quot;:&quot;test1&quot;}]}

I have provided complete reference code which I am using with proper URL and data, please help me on this

答案1

得分: 0

以下是翻译好的部分:

  1. As you tell the API what result you want with the withID variable you can decode the data conditionally.
    当你使用 withID 变量告诉 API 你想要什么结果时,你可以有条件地解码数据。

  2. And it's recommended to call the failure case of completion on any error you get.
    推荐在遇到任何错误时调用 completionfailure 情况。

  3. func getUsers(completion: @escaping (Result<[ResultItem], Error>) -> ()) {
    func getUsers(completion: @escaping (Result<[ResultItem], Error>) -> ()) {

  4. var uri = "test"
    var uri = "test"

  5. if !withID.isEmpty {
    if !withID.isEmpty {

  6. uri += "withID"
    uri += "withID"

  7. let method = GET
    let method = GET

  8. let urlString = "https:myownURL(uri)"
    let urlString = "https:myownURL(uri)"

  9. generates a header
    生成一个头部

  10. URLSession.shared.dataTask(with: urlHeader) { (data, _ , error) in
    URLSession.shared.dataTask(with: urlHeader) { (data, _ , error) in

  11. if let error { completion(.failure(error)); return }
    if let error { completion(.failure(error)); return }

  12. print(String(data: data!, encoding: .utf8) ?? "Invalid JSON")
    print(String(data: data!, encoding: .utf8) ?? "Invalid JSON")

  13. do {
    do {

  14. let results = try JSONDecoder().decode(ResultItem.self,from: data!)
    let results = try JSONDecoder().decode(ResultItem.self, from: data!)

  15. completion(.success([results]))
    completion(.success([results]))

  16. let results = try JSONDecoder().decode(Results.self,from: data!)
    let results = try JSONDecoder().decode(Results.self, from: data!)

  17. completion(.success(results.userInfo))
    completion(.success(results.userInfo))

  18. } catch {
    } catch {

  19. completion(.failure(error))
    completion(.failure(error))

  20. }.resume()
    }.resume()

英文:

As you tell the API what result you want with the withID variable you can decode the data conditionally.

And it's recommended to call the failure case of completion on any error you get.

func getUsers(completion: @escaping (Result&lt;[ResultItem],Error&gt;) -&gt; ()) {
    var uri = &quot;\test&quot;
    if !withID.isEmpty {
        uri += &quot;\withID&quot;
    } 
    
    let method = GET
    let urlString = &quot;https:myownURL\(uri)&quot;
    
    //generates a header
    let urlHeader = headersGenerator()
    
    URLSession.shared.dataTask(with: urlHeader) { (data, _ , error) in
        if let error { completion(.failure(error)); return }
        print(String(data: data!, encoding: .utf8) ?? &quot;Invalid JSON&quot;)
        do {
            if !withID.isEmpty {
                let results = try JSONDecoder().decode(ResultItem.self,from: data!)
                completion(.success([results]))
            } else {
                let results = try JSONDecoder().decode(Results.self,from: data!)
                completion(.success(results.userInfo))
            }
        } catch {
            completion(.failure(error))
        }
    }.resume()
}

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

发表评论

匿名网友

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

确定