원격 디스플레이 JSON 파일의 SwiftUI 중간 목록 (2020 자습서)

원격 디스플레이 JSON 파일의 SwiftUI 중간 목록 (2020 자습서)

이것의 목적은 목록 SwiftUI 디스플레이에서 원격 파일 및 JSON의 간단한 방법에서 데이터를 얻을 수있는 방법을 보여주는 것입니다.

데이터 프리젠 테이션

다음 형식으로 우리의 JSON 파일입니다

[{
    "id": 5,
    "title": "Joker",
    "year": "2019",
    "image": "",
    "created_at": "2019-10-06T17:55:21.374Z",
    "updated_at": "2019-10-06T17:55:21.374Z"
}, {
    "id": 1,
    "title": "Pulp Fiction",
    "year": "1994",
    "image": "",
    "created_at": "2019-10-06T15:26:36.675Z",
    "updated_at": "2019-10-06T18:05:31.649Z"
}, {
    "id": 4,
    "title": " The Godfather ",
    "year": "1972",
    "image": "",
    "created_at": "2019-10-06T15:27:38.123Z",
    "updated_at": "2019-10-06T18:05:50.242Z"
}, {
    "id": 6,
    "title": "The Dark Knight ",
    "year": "2008",
    "image": "",
    "created_at": "2019-10-06T18:06:12.933Z",
    "updated_at": "2019-10-06T18:06:12.933Z"
}, {
    "id": 7,
    "title": "Fight Club",
    "year": "1999",
    "image": "",
    "created_at": "2019-10-06T18:06:33.096Z",
    "updated_at": "2019-10-06T18:06:33.096Z"
}, {
    "id": 8,
    "title": " Inception",
    "year": "2010",
    "image": "",
    "created_at": "2019-10-06T18:06:52.034Z",
    "updated_at": "2019-10-06T18:06:52.034Z"
}, {
    "id": 2,
    "title": "The Matrix ",
    "year": "1999",
    "image": "",
    "created_at": "2019-10-06T15:26:48.042Z",
    "updated_at": "2019-10-06T18:08:00.902Z"
}, {
    "id": 3,
    "title": "The Shawshank Redemption ",
    "year": "1984",
    "image": "",
    "created_at": "2019-10-06T15:26:59.572Z",
    "updated_at": "2019-10-06T18:08:47.637Z"
}]

예상 결과

코딩

첫째, 우리는이 경우, 모델은 복호 및 식별 동의 구조체이며, 영화 모델을 정의해야합니다. 이 JSON 파일에서 디코딩 할 수 복호, 식별이 목록으로 나열 할 수 있습니다. 데이터 수집의 목록을 표시 할 수있는 목록이있는 UITableViewController 동일하게 식별 할 수 있습니다.

struct Movie: Decodable, Identifiable {
    public var id: Int
    public var name: String
    public var released: String
    
    enum CodingKeys: String, CodingKey {
           case id = "id"
           case name = "title"
           case released = "year"
        }
}

JSON 주요 변수 이름 모델명 할 수있는 CodingKeys 당신은지도를 만들었습니다. 이 경우, 나는 그것이 몇 년 대신 해제 당신이 당신이 키가 될 수 있습니다 코딩에 그것을 정의로, 모델에서 자신의 이름을 사용할 수 있음을 보여 지명했다.

우리는 데이터를 읽을 아래 코드와 코드를 디코딩

public class MovieFetcher: ObservableObject {
    @Published var movies = [Movie]()
    
    init(){
        load()
    }
    
    func load() {
        let url = URL(string: "https://gist.githubusercontent.com/rbreve/60eb5f6fe49d5f019d0c39d71cb8388d/raw/f6bc27e3e637257e2f75c278520709dd20b1e089/movies.json")!
    
        URLSession.shared.dataTask(with: url) {(data,response,error) in
            do {
                if let d = data {
                    let decodedLists = try JSONDecoder().decode([Movie].self, from: d)
                    DispatchQueue.main.async {
                        self.movies = decodedLists
                    }
                }else {
                    print("No Data")
                }
            } catch {
                print ("Error")
            }
            
        }.resume()
         
    }
}

결합 프레임 워크는 시간 값을 처리, 선언적 스위프트 API를 제공합니다. 이 값은 비동기 다양한 이벤트를 나타낼 수 있습니다. 시간에 따라 변화하는 값으로 발표 공문을 결합, 가입자가 게시자에서이 값을받을 수 있습니다.
@ObervableObject : 게시자 기능을 가진 객체, 객체 변화 문제 전의 객체입니다. 기본적으로 @ ObservableObject는 어떤 변화가 @Published 속성에서 발생하기 전에 게시자는 값을 변경 발급됩니다하는 objectWillChange 게시자를 합성한다.
영화는 모든 ObserableObject에게 통지합니다 때 @Published 수정 영화 후 배열이 변경됩니다.

데이터 우리 어레이 넣어 동영상에 할당하는로드되면 부하 () 메소드 JSON 비동기 데이터는 네트워크로부터 취득. 때 가입자에게 이벤트를 보냅니다 변화의 영화 배열입니다.

struct ContentView: View {
    @ObservedObject var fetcher = MovieFetcher()
    
    var body: some View {
        VStack {
            List(fetcher.movies) { movie in
                VStack (alignment: .leading) {
                    Text(movie.name)
                    Text(movie.released)
                        .font(.system(size: 11))
                        .foregroundColor(Color.gray)
                }
            }
        }
    }
}

전체 코드


import Foundation
import SwiftUI
import Combine
 
public class MovieFetcher: ObservableObject {

    @Published var movies = [Movie]()
    
    init(){
        load()
    }
    
    func load() {
        let url = URL(string: "https://gist.githubusercontent.com/rbreve/60eb5f6fe49d5f019d0c39d71cb8388d/raw/f6bc27e3e637257e2f75c278520709dd20b1e089/movies.json")!
    
        URLSession.shared.dataTask(with: url) {(data,response,error) in
            do {
                if let d = data {
                    let decodedLists = try JSONDecoder().decode([Movie].self, from: d)
                    DispatchQueue.main.async {
                        self.movies = decodedLists
                    }
                }else {
                    print("No Data")
                }
            } catch {
                print ("Error")
            }
            
        }.resume()
         
    }
}

struct Movie: Codable, Identifiable {
    public var id: Int
    public var name: String
    public var released: String
    
    enum CodingKeys: String, CodingKey {
           case id = "id"
           case name = "title"
           case released = "year"
        }
}


struct ListJsonView: View {
    @ObservedObject var fetcher = MovieFetcher()
    
    var body: some View {
        VStack {
            List(fetcher.movies) { movie in
                VStack (alignment: .leading) {
                    Text(movie.name)
                    Text(movie.released)
                        .font(.system(size: 11))
                        .foregroundColor(Color.gray)
                }
            }
        }
    }
}

 


struct ListJsonView__Previews: PreviewProvider {
    static var previews: some View {
        ListJsonView()
    }
}

참조

주의 SwiftUI 자습서 및 코드 열을 더

게시 된 637 개 원래 기사 · 원 찬양 4 ·은 50000 +를 볼

추천

출처blog.csdn.net/iCloudEnd/article/details/104079667