view LazyBear/UI/NewsView.swift @ 258:471906e56feb

Changing NewsView on iPad
author Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com>
date Fri, 12 Mar 2021 20:48:42 +0100
parents 2d7ad67a3e95
children 23e48c2d153d
line wrap: on
line source

//
//  NewsView.swift
//  LazyBear
//
//  Created by Dennis Concepción Martín on 20/2/21.
//

import SwiftUI
import WaterfallGrid

struct NewsView: View {
    var symbol: String
    @FetchRequest(entity: UserSettings.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \UserSettings.changedAt, ascending: false)])
    var userSettings: FetchedResults<UserSettings>
    @State private var news = [NewsModel]()
    
    var body: some View {
        VStack(alignment: .leading) {
            if !news.isEmpty {
                HStack {
                    Image(systemName: "newspaper.fill")
                        .foregroundColor(Color(.systemTeal))
                        .imageScale(.large)
                    
                    Text("Recent news")
                        .font(.title2)
                        .fontWeight(.semibold)
                    
                    Spacer()
                }
                .padding()
            }
            
            let language = userSettings.first?.newsLanguage ?? "en"
            
            // If iPhone
            if UIDevice.current.userInterfaceIdiom == .phone {
                ForEach(news, id: \.self) { new in
                    if language == new.lang {
                        NewsRow(new: new)
                          .padding(.horizontal)
                        
                        Divider()
                    }
                }
            }
            
            // If iPad
            if UIDevice.current.userInterfaceIdiom == .pad {
                WaterfallGrid(news, id: \.self) { new in
                    NewsRow(new: new)
                }
                .gridStyle(
                    columnsInPortrait: 2,
                    columnsInLandscape: 3,
                    spacing: 8,
                    animation: .easeInOut(duration: 0.5)
                  )
                .padding(EdgeInsets(top: 16, leading: 8, bottom: 16, trailing: 8))
            }
        }
        .onAppear {
            request(url: getUrl(), model: [NewsModel].self) { self.news = $0 }
        }
    }
    
    private func getUrl() -> String {
        let baseUrl = Bundle.main.infoDictionary?["IEX_URL"] as? String ?? "Empty url"
        let apiKey = Bundle.main.infoDictionary?["IEX_API"] as? String ?? "Empty key"
        let url = "\(baseUrl)/stock/\(symbol)/news/last/30?token=\(apiKey)"

        return url
    }
}


struct NewsView_Previews: PreviewProvider {
    static var previews: some View {
        NewsView(symbol: "aapl")
    }
}