如何在Swift中用单个Model显示不同形式的数据

ewm0tg9j  于 2023-04-04  发布在  Swift
关注(0)|答案(1)|浏览(109)

我有一个函数的API请求如下

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)"
        
//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) ?? "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
}

当我不传递withID时,这会给我一个正确的响应,如下所示(URL将是https:myownURL.test)
输出如下所示

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

但是如果我运行带有withID的url(url将是https:myownURL.test.withID),输出应该给予一个值,我得到的是一个值,但是格式不同

{"userId":"0390","userlastname":"test1","username":"test1"}

但是两个API的模型是相同的,因此它应该返回如下响应

{"userInfo":[{"userId":"0390","userlastname":"test1","username":"test1"}]}

请让我知道我做错了什么,这样的React会是这样的

{"userInfo":[{"userId":"0390","userlastname":"test1","username":"test1"}]}

我已经提供了完整的参考代码,我正在使用适当的网址和数据,请帮助我在这一点上

qco9c6ql

qco9c6ql1#

当你告诉API你想要的withID变量的结果时,你可以有条件地解码数据。
并且建议在遇到任何错误时调用completionfailure case。

func getUsers(completion: @escaping (Result<[ResultItem],Error>) -> ()) {
    var uri = "\test"
    if !withID.isEmpty {
        uri += "\withID"
    } 
    
    let method = GET
    let urlString = "https:myownURL\(uri)"
    
    //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) ?? "Invalid JSON")
        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()
}

相关问题