จะให้ฉันใช้คนใหม่หาวิธีการสำหรับอีกแบบ?

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 ต้อง conform คือ 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ý
..................................................................................................................

ดังอยู่ในนี้หมวดหมู่

ดังคำถามอยู่ในนี้หมวดหมู่