< 작업 환경 >

 

 

 

 

 

 

1. Model 파일

 


import Foundation

// 경제 뉴스


// MARK: - StockNewsM

struct StockNewsM: Codable {
    let status: StatusOfApiM
    let result: ResultOfStockNews
}

struct StatusOfApiM: Codable {
    let status, message: String
}

struct ResultOfStockNews: Codable {
    let totalData: Int
    let marketNewsList: [MarketNewsList]
}



struct MarketNewsList: Codable {
    let newsId = UUID()
    let link, title, date, source: String?
}

 

 - 데이터 형태 예시 (참고)

{
  "status": {
    "status": "E000",
    "message": "Success"
  },
  "result": {
    "totalData": 50,
    "marketNewsList": [
      {
        "link": "https://finance.yahoo.com/news/first-republic-pursues-strategic-options-201303351.html",
        "title": "First Republic to Shrink as Deposits Drop More Than Expected",
        "date": "18hours ago",
        "source": "Bloomberg"
      },
      {
        "link": "https://www.wsj.com/articles/first-republic-lost-100-billion-in-deposits-in-banking-panic-7e1bd86c?siteid=yhoof2&yptr=yahoo",
        "title": "First Republic Lost $100 Billion in Deposits in Banking Panic",
        "date": "19hours ago",
        "source": "The Wall Street Journal"
      },
      {
        "link": "https://www.barrons.com/articles/amazon-microsoft-alphabet-meta-big-tech-earnings-fa13851?siteid=yhoof2&yptr=yahoo",
        "title": "Big Tech Earnings Are Coming. What to Know About Amazon, Microsoft, Alphabet, and Meta.",
        "date": "19hours ago",
        "source": "Barrons.com"
      },
      {
        "link": "https://www.investopedia.com/first-republic-deposits-plunge-q1-fy2023-7484537?utm_campaign=quote-yahoo&utm_source=yahoo&utm_medium=referral&yptr=yahoo",
        "title": "First Republic to Cut Staff After 40% Plunge in Deposits",
        "date": "19hours ago",
        "source": "Investopedia"
      },
      {
        "link": "https://www.wsj.com/articles/first-republic-joins-the-living-dead-3a7704ec?siteid=yhoof2&yptr=yahoo",
        "title": "First Republic Joins the Living Dead",
        "date": "20hours ago",
        "source": "The Wall Street Journal"
      },
      {
        "link": "https://finance.yahoo.com/news/bmo-says-panic-over-recession-215211551.html",
        "title": "‘Panic Over Recession Is Overblown,’ Says BMO — Now Might Be an Opportune Time to Jump Into These 2 Stocks",
        "date": "20hours ago",
        "source": "TipRanks"
      },
      {
        "link": "https://www.barrons.com/articles/verizon-earnings-stock-price-47915ac4?siteid=yhoof2&yptr=yahoo",
        "title": "Verizon Earnings Arrive as Industry Growth Cools",
        "date": "20hours ago",
        "source": "Barrons.com"
      },
      {
        "link": "https://www.wsj.com/articles/cnbc-anchor-alleged-nbcuniversal-jeff-shell-boss-sexually-harassed-her-prompting-his-exit-b7645496?siteid=yhoof2&yptr=yahoo",
        "title": "CNBC Anchor Alleged NBCUniversal Boss Jeff Shell Sexually Harassed Her, Prompting His Exit",
        "date": "20hours ago",
        "source": "The Wall Street Journal"
      },
      {
        "link": "https://finance.yahoo.com/news/stocks-moving-after-hours-first-republic-whirlpool-cleveland-cliffs-212236903.html",
        "title": "Stocks moving after hours: First Republic, Whirlpool, Cleveland-Cliffs",
        "date": "20hours ago",
        "source": "Yahoo Finance"
      },
      {
        "link": "https://finance.yahoo.com/news/tesla-investors-worried-elon-musk-211000648.html",
        "title": "Tesla investors are worried Elon Musk enjoys operating \"above the law\"",
        "date": "20hours ago",
        "source": "Quartz"
      },
      {
        "link": "https://www.investors.com/news/technology/cdns-stock-cadence-design-systems-beats-views-but-gives-weak-guidance/?src=A00220&yptr=yahoo",
        "title": "Cadence Design Systems Beats First-Quarter Views But Gives Weak Guidance",
        "date": "20hours ago",
        "source": "Investor's Business Daily"
      },
      {
        "link": "https://www.wsj.com/articles/corporate-insiders-step-up-stock-buying-after-banking-turmoil-6eabb6d7?siteid=yhoof2&yptr=yahoo",
        "title": "Corporate Insiders Step Up Stock Buying After Banking Turmoil",
        "date": "21hours ago",
        "source": "The Wall Street Journal"
      },
      {
        "link": "https://finance.yahoo.com/news/bud-light-executives-put-leave-203300252.html",
        "title": "Bud Light executives put on leave after Dylan Mulvaney uproar",
        "date": "21hours ago",
        "source": "CBS MoneyWatch"
      },
      {
        "link": "https://www.investors.com/market-trend/stock-market-today/dow-jones-flat-as-microsoft-intel-slip-fox-stock-skids-on-tucker-carlson-departure/?src=A00220&yptr=yahoo",
        "title": "Dow Jones Up As Fox Skids On Tucker Carlson Exit; First Republic Dives; 3 Stocks Near Buy Points",
        "date": "21hours ago",
        "source": "Investor's Business Daily"
      },
      {
        "link": "https://finance.yahoo.com/news/tucker-carlson-fox-news-exit-162319291.html",
        "title": "Tucker Carlson’s Fox News Exit Erases $507 Million in Value",
        "date": "21hours ago",
        "source": "Bloomberg"
      },
      {
        "link": "https://finance.yahoo.com/news/first-republic-lost-72-billion-in-deposits-amid-bank-turmoil-201258847.html",
        "title": "First Republic lost $72 billion in deposits amid bank turmoil",
        "date": "21hours ago",
        "source": "Yahoo Finance"
      },
      {
        "link": "https://finance.yahoo.com/news/microsoft-earnings-ai-hype-could-take-backseat-to-cloud-growth-troubles-201023413.html",
        "title": "Microsoft earnings: AI hype could take backseat to cloud growth troubles",
        "date": "21hours ago",
        "source": "Yahoo Finance"
      },
      {
        "link": "https://finance.yahoo.com/news/tesla-just-made-unknown-family-200657593.html",
        "title": "Tesla Just Made This Unknown Family $1.2 Billion",
        "date": "21hours ago",
        "source": "Benzinga"
      },
      {
        "link": "https://www.investors.com/news/technology/smci-stock-super-micro-computer-tumbles-on-sales-warning/?src=A00220&yptr=yahoo",
        "title": "Super Micro Computer Stock Tumbles After Warning Of Sales Shortfall",
        "date": "21hours ago",
        "source": "Investor's Business Daily"
      },
      {
        "link": "https://www.investors.com/news/ge-earnings-due-tuesday-as-divorced-ge-gehc-stock-rally/?src=A00220&yptr=yahoo",
        "title": "Divorce Sets GE/GEHC Free, Stocks Soar; Earnings Due Tuesday",
        "date": "21hours ago",
        "source": "Investor's Business Daily"
      },
      {
        "link": "https://finance.yahoo.com/news/satoshi-era-bitcoin-whale-moves-185907607.html",
        "title": "Satoshi-Era Bitcoin Whale Moves $11 Million After Sleeping for 12 Years",
        "date": "22hours ago",
        "source": "Decrypt Media"
      },
      {
        "link": "https://finance.yahoo.com/news/alphabet-earnings-ai-cost-cuts-take-center-stage-185507416.html",
        "title": "Alphabet earnings: AI, cost cuts take center stage",
        "date": "23hours ago",
        "source": "Yahoo Finance"
      },
      {
        "link": "https://www.investors.com/research/ark-invest-stocks/?src=A00220&yptr=yahoo",
        "title": "Best Cathie Wood Stocks To Watch: Coinbase, Block, Roku, Zoom Video; Tesla Skids",
        "date": "23hours ago",
        "source": "Investor's Business Daily"
      },
      {
        "link": "https://finance.yahoo.com/news/shale-gas-drillers-brace-8-163251184.html",
        "title": "Shale-Gas Drillers Brace for $8 Billion Cash-Flow Shock on Price Drop",
        "date": "1days ago",
        "source": "Bloomberg"
      },
      {
        "link": "https://www.investopedia.com/savings-account-or-cd-whats-smarter-right-now-7483454?utm_campaign=quote-yahoo&utm_source=yahoo&utm_medium=referral&yptr=yahoo",
        "title": "Savings Account or CD: What’s Smarter Right Now?",
        "date": "1days ago",
        "source": "Investopedia"
      },
      {
        "link": "https://finance.yahoo.com/news/gm-earnings-preview-more-sales-more-profit-and-a-spotlight-on-evs-161922589.html",
        "title": "GM Earnings preview: More sales, more profit and a spotlight on EVs",
        "date": "1days ago",
        "source": "Yahoo Finance"
      },
      {
        "link": "https://www.barrons.com/articles/rivian-stock-evs-downgrade-sell-9e4afaa0?siteid=yhoof2&yptr=yahoo",
        "title": "Rivian Stock Is Making New Lows. Sell It Anyway, Say Analysts.",
        "date": "1days ago",
        "source": "Barrons.com"
      },
      {
        "link": "https://finance.yahoo.com/news/johnson-johnson-unleashes-kenvue-tylenol-141952178.html",
        "title": "Johnson & Johnson Unleashes Kenvue: Tylenol to Neutrogena, $40B Revenue Unit Spinoff Preps for IPO Blitz",
        "date": "1days ago",
        "source": "Benzinga"
      },
      {
        "link": "https://finance.yahoo.com/news/banks-paying-savers-again-many-141818834.html",
        "title": "Banks are paying savers again after many years of low rates",
        "date": "1days ago",
        "source": "AP Finance"
      },
      {
        "link": "https://finance.yahoo.com/news/goldman-sachs-likes-2-top-133156293.html",
        "title": "Goldman Sachs Likes These 2 Top Dividend Stocks Yielding as High as 10%",
        "date": "1days ago",
        "source": "TipRanks"
      },
      {
        "link": "https://finance.yahoo.com/news/bad-news-too-many-people-131552946.html",
        "title": "Bad News: Too Many People Are Cashing Out Their 401(k) Plans",
        "date": "1days ago",
        "source": "SmartAsset"
      },
      {
        "link": "https://finance.yahoo.com/news/way-irs-operates-undergo-major-203340053.html",
        "title": "The way the IRS operates is about to undergo a major change. Here's what that means for you",
        "date": "1days ago",
        "source": "USA TODAY"
      },
      {
        "link": "https://finance.yahoo.com/news/fearful-millennials-missed-stock-market-130202111.html",
        "title": "Fearful Millennials Missed Stock Market Rally With Shift to Cash",
        "date": "1days ago",
        "source": "Bloomberg"
      },
      {
        "link": "https://finance.yahoo.com/news/sibling-inherited-ira-split-130034957.html",
        "title": "My Sibling and I Inherited an IRA. How Do We Split It?",
        "date": "1days ago",
        "source": "SmartAsset"
      },
      {
        "link": "https://finance.yahoo.com/news/retire-comfortably-45-5-million-130026468.html",
        "title": "Can I Retire Comfortably at 45 with $5 Million?",
        "date": "1days ago",
        "source": "SmartAsset"
      },
      {
        "link": "https://finance.yahoo.com/news/morgan-stanley-analysts-think-commercial-123220700.html",
        "title": "Morgan Stanley analysts think commercial real estate is heading for something ‘worse than in the Great Financial Crisis’—here’s what Goldman Sachs and UBS have to say",
        "date": "1days ago",
        "source": "Fortune"
      },
      {
        "link": "https://www.investors.com/etfs-and-funds/sectors/sp500-att-is-no-longer-the-highest-yielding-free-cash-flow-powerhouse/?src=A00220&yptr=yahoo",
        "title": "AT&T Is No Longer The Highest-Yielding Free-Cash-Flow Powerhouse",
        "date": "1days ago",
        "source": "Investor's Business Daily"
      },
      {
        "link": "https://www.wsj.com/articles/weapons-makers-cant-hire-enough-workers-as-ukraine-war-drives-demand-d1b74bee?siteid=yhoof2&yptr=yahoo",
        "title": "Weapons Makers Can’t Hire Enough Workers as Ukraine War Drives Demand",
        "date": "1days ago",
        "source": "The Wall Street Journal"
      },
      {
        "link": "https://finance.yahoo.com/news/bud-light-marketing-leadership-adjustments-203931914.html",
        "title": "Bud Light marketing leadership 'adjustments' made after conservative boycott threats",
        "date": "1days ago",
        "source": "USA TODAY"
      },
      {
        "link": "https://www.barrons.com/articles/fed-pause-rates-stocks-may-not-rally-77908b65?siteid=yhoof2&yptr=yahoo",
        "title": "A Fed Pause Is Coming. Stocks May Not Rally When It Arrives.",
        "date": "1days ago",
        "source": "Barrons.com"
      },
      {
        "link": "https://finance.yahoo.com/news/lithium-refining-lacks-supply-according-231451494.html",
        "title": "Lithium Refining Lacks Supply, According to Elon Musk — Here Are 2 Stocks to Take Advantage",
        "date": "1days ago",
        "source": "TipRanks"
      },
      {
        "link": "https://finance.yahoo.com/news/cheaper-teslas-hurting-profits-elon-150000305.html",
        "title": "Cheaper Teslas are hurting profits, but Elon Musk plans to keep slashing prices. Here's why.",
        "date": "1days ago",
        "source": "Business Insider"
      },
      {
        "link": "https://finance.yahoo.com/news/commercial-real-estate-market-wobbling-204500832.html",
        "title": "The commercial real estate market is wobbling, and 2 of the largest players are feeling the pain of higher rates and tighter credit",
        "date": "1days ago",
        "source": "Business Insider"
      },
      {
        "link": "https://www.barrons.com/articles/bud-light-exec-takes-leave-after-boycott-calls-15a86829?siteid=yhoof2&yptr=yahoo",
        "title": "Two Bud Light Execs Leave After Calls to Boycott",
        "date": "1days ago",
        "source": "Barrons.com"
      },
      {
        "link": "https://finance.yahoo.com/news/7-signals-suggest-bullish-cocktail-201500183.html",
        "title": "Here are the 7 signals that suggest a 'bullish cocktail' is about to power a surprise rally in the stock market",
        "date": "1days ago",
        "source": "Business Insider"
      },
      {
        "link": "https://finance.yahoo.com/news/mortgage-fees-changing-homebuyers-next-180651521.html",
        "title": "Mortgage fees are changing for homebuyers next month. Here's what you should know.",
        "date": "1days ago",
        "source": "USA TODAY"
      },
      {
        "link": "https://finance.yahoo.com/news/much-interest-earn-1-million-150000229.html",
        "title": "Will I Be Able to Live Off The Interest of My $1 Million Portfolio?",
        "date": "2days ago",
        "source": "SmartAsset"
      },
      {
        "link": "https://finance.yahoo.com/news/capital-gains-inherited-property-203623927.html",
        "title": "Some Good News: If You Inherit Property, You Don't Pay Taxes Automatically",
        "date": "2days ago",
        "source": "SmartAsset"
      },
      {
        "link": "https://finance.yahoo.com/news/rich-avoid-paying-taxes-savings-150055760.html",
        "title": "How The Rich Avoid Paying Savings Account Taxes",
        "date": "2days ago",
        "source": "SmartAsset"
      },
      {
        "link": "https://finance.yahoo.com/news/foxs-settlement-dominion-unlikely-cost-120054140.html",
        "title": "Fox's settlement with Dominion unlikely to cost it $787.5M",
        "date": "2days ago",
        "source": "AP Finance"
      }
    ]
  }
}

 

 

 

 

 

2. Control or ViewModel 파일

 

// Stock

import Foundation


// 경제 뉴스 : news
class StockNewsVM: ObservableObject {
    @Published var stockNews: StockNewsM?
    
    // check Optional
    private var urlOptional: URL?
    
    init(api_url: String) {
        guard let components = URLComponents(string: "\(api_url)/v2/stock/news/market?lang=en") else {
            print("Invalid URL")
            return
        }
        
        guard let url = components.url else {
            print("Failed to create URL")
            return
        }
        
        urlOptional = url
    }
    public func getData(completion: @escaping (StockNewsM?) -> Void) {
        if let targetUrl = urlOptional {
            var request = URLRequest(url: targetUrl)
            request.httpMethod = "GET"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
                guard data == data else {
                    print("Error: \(error!)")
                    return
                }
                
                guard let data = data else {
                    print("No data received")
                    return
                }

                do {
                    let responseDecoded = try JSONDecoder().decode(StockNewsM.self, from: data)
                    DispatchQueue.main.async {
                        self.stockNews = responseDecoded
                    }
                } catch {
                    print("\n\n[Error Decoding Response] StockNewsVM\n\n\(error.localizedDescription)\n\n\(error)")
                }
            })
            .resume()
        } else {
            print("if let urlOptional 오류")
        }
    }
}

 

 

 

 

 

3. View 파일

 

// ContentView.swift


import SwiftUI

// 경제 뉴스
struct MoneyTopTabThirdNews: View {
    
    @State private var isActive: Bool = false
    @State private var selectedUrl: String = ""
    @ObservedObject var newsData: StockNewsVM
    
    init() {
        self.newsData = StockNewsVM(api_url: api_url)
        self.loadNewsInfoData()
    }
    
    func loadNewsInfoData() {
        newsData.getData(completion: {data in
            DispatchQueue.main.async {
                self.newsData.stockNews = data
            }
        })
    }
    
    var body: some View {
        if let stockNews = newsData.stockNews {
            // 뉴스 기사가 없을 때
            if stockNews.result.totalData == 0 {
                Text("뉴스 기사가 없어요")
                    .foregroundColor(Color.gray600)
                    .font(.custom(pretendard_regular, size: 20))
            // 뉴스 기사가 있을 때
            } else {
                NavigationLink(destination: StartOpenWebView(targetUrl:selectedUrl), isActive: $isActive, label: { EmptyView() } )
                ForEach(stockNews.result.marketNewsList, id: \.newsId) { eachNews in
                    VStack {
                        Text(eachNews.title ?? "")
                            .foregroundColor(Color.black)
                            .font(.custom(pretendard_regular, size: 18))
                            .frame(width: 350, alignment: .topLeading)
                            .padding(.horizontal, 20)
                        HStack {
                            Spacer()
                            Text(eachNews.source ?? "")
                                .foregroundColor(Color.gray600)
                                .font(.custom(pretendard_regular, size: 18))
                        }
                        .padding(.horizontal, 20)
                        HStack {
                            Spacer()
                            Text(eachNews.date ?? "")
                                .foregroundColor(Color.gray4)
                                .font(.custom(pretendard_regular, size: 18))
                        }
                        .padding(.horizontal, 20)
                    }
                    .padding(10)
                    .onTapGesture {
                        isActive = true
                        selectedUrl = eachNews.link ?? ""
                    }
                }
                .onAppear {
                    DispatchQueue.main.async {
                        self.loadNewsInfoData()
                    }
                }
            }
        }
    }
}

 

 

 

 

+ Recent posts