어떻게 사용할 수 있는 이 새로운 방법에 대한 다른 모델?

0

질문

class Network {
    func getingData(completion : @escaping ([Model]) -> ()) async {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return }
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            if let posts = try? JSONDecoder().decode([Model].self, from: data) {
                completion(posts)
            }
        }
        catch {
            print("error")
        }
    }
}
ios swiftui urlsession
2021-11-22 06:27:47
2

최고의 응답

0

당신이 시도할 수 있습이 같은 접근 방식 getData 작동 Decodable로 언급되었에서 이전의 대답이다. 이 예제에서는 배열의 Decodable.

struct Post: Decodable, Identifiable {
    let userId: Int
    let id: Int
    let title: String
    let body: String
    var comments: [Comment]?
}

struct Comment: Decodable, Identifiable {
    let postId: Int
    let id: Int
    let name: String
    let email: String
    let body: String
}

struct ContentView: View {
    let client = Network()
    @State var posts: [Post] = []  
    
    var body: some View {
        List {
            ForEach(posts, id: \.id) { post in
                Text(post.title)
            }
        }
        .task {
            posts = await client.getData(from: "https://jsonplaceholder.typicode.com/posts")
            // all comments from the first post
            let comments: [Comment] = await client.getData(from: "https://jsonplaceholder.typicode.com/posts/\(posts[0].id)/comments")
            print("\n---> comments: \(comments)")
        }
    }
}

class Network {

    func getData<T: Decodable>(from urlString: String) async -> [T] {
        guard let url = URL(string: urlString) else {
            print(URLError(.badURL))
            return [] // <-- todo, deal with errors
        }
        do {
            let (data, response) = try await URLSession.shared.data(for: URLRequest(url: url))
            guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
                print(URLError(.badServerResponse))
                return [] // <-- todo, deal with errors
            }
            let results = try JSONDecoder().decode([T].self, from: data)
            return results
        }
        catch {
            return [] // <-- todo, deal with errors
        }
    }
    
}
2021-11-22 07:56:28
0

그것이 무엇을 찾고 계신가?

import Foundation

class Network {

  func getingData<Model: Decodable>(completion : @escaping ([Model]) -> ()) async {
    guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {
      return
    }
    do {
      let (data, _) = try await URLSession.shared.data(from: url)
      if let posts = try? JSONDecoder().decode([Model].self, from: data) {
        completion(posts)
      }
    } catch {
      print("error")
    }
  }

}

그렇다면,당신은 당신만을 선언 Model 종류로 일반적이다. 당신이 필요로하는 유일한 것은 Model 을 준수이 Decodable (의 요구 사항 JSONDecoder().decode([Model].self, from: data) 전화).

2021-11-22 07:29:35

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................