英文:
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<[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()
}
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
{"userInfo":[{"userId":"0390","userlastname":"test1","username":"test1"},{"userId":"0391","userlastname":"test2","username":"test2"},{"userId":"0392","userlastname":"test3","username":"test3"}]}
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
{"userId":"0390","userlastname":"test1","username":"test1"}
but the model is same for both API so that it should return response as below
{"userInfo":[{"userId":"0390","userlastname":"test1","username":"test1"}]}
please let me know what mistake I am doing so that the response will come like this
{"userInfo":[{"userId":"0390","userlastname":"test1","username":"test1"}]}
I have provided complete reference code which I am using with proper URL and data, please help me on this
答案1
得分: 0
以下是翻译好的部分:
-
As you tell the API what result you want with the
withID
variable you can decode the data conditionally.
当你使用withID
变量告诉 API 你想要什么结果时,你可以有条件地解码数据。 -
And it's recommended to call the
failure
case ofcompletion
on any error you get.
推荐在遇到任何错误时调用completion
的failure
情况。 -
func getUsers(completion: @escaping (Result<[ResultItem], Error>) -> ()) {
func getUsers(completion: @escaping (Result<[ResultItem], Error>) -> ()) { -
var uri = "test"
var uri = "test" -
if !withID.isEmpty {
if !withID.isEmpty { -
uri += "withID"
uri += "withID" -
let method = GET
let method = GET -
let urlString = "https:myownURL(uri)"
let urlString = "https:myownURL(uri)" -
generates a header
生成一个头部 -
URLSession.shared.dataTask(with: urlHeader) { (data, _ , error) in
URLSession.shared.dataTask(with: urlHeader) { (data, _ , error) in -
if let error { completion(.failure(error)); return }
if let error { completion(.failure(error)); return } -
print(String(data: data!, encoding: .utf8) ?? "Invalid JSON")
print(String(data: data!, encoding: .utf8) ?? "Invalid JSON") -
do {
do { -
let results = try JSONDecoder().decode(ResultItem.self,from: data!)
let results = try JSONDecoder().decode(ResultItem.self, from: data!) -
completion(.success([results]))
completion(.success([results])) -
let results = try JSONDecoder().decode(Results.self,from: data!)
let results = try JSONDecoder().decode(Results.self, from: data!) -
completion(.success(results.userInfo))
completion(.success(results.userInfo)) -
} catch {
} catch { -
completion(.failure(error))
completion(.failure(error)) -
}.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<[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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论