Last active
February 10, 2026 18:27
-
-
Save codewithsanthoshofficial/317006195b1faa584d5549bd54aa2767 to your computer and use it in GitHub Desktop.
API call _ SwiftUI _Codable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| enum APIEndPoint { | |
| static let baseURL = "" | |
| case news | |
| var url:String { | |
| switch self { | |
| case .news: return "\(APIEndPoint.baseURL)+news" | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| class APIService { | |
| static let shared = APIService() | |
| private init() {} | |
| func request<T:Codable>(enpoint:String, method:String = "GET", body:Data? = nil, completion:@escaping (Result<T, Error>) -> Void) { | |
| guard let url = URL(string: enpoint) else { | |
| completion(.failure(NSError(domain: "Invalid URL", code: 400))) | |
| return | |
| } | |
| var request = URLRequest(url: url) | |
| request.httpMethod = method | |
| request.httpBody = body | |
| request.addValue("application/json", forHTTPHeaderField: "Content-Type") | |
| URLSession.shared.dataTask(with: request) { data, response , error in | |
| if let error = error { | |
| completion(.failure(error)) | |
| return | |
| } | |
| guard let data = data else { | |
| completion(.failure(NSError(domain: "No Data", code: 404))) | |
| return | |
| } | |
| do { | |
| let decoded = try JSONDecoder().decode(T.self, from: data) | |
| completion(.success(decoded)) | |
| } | |
| catch { | |
| completion(.failure(error)) | |
| } | |
| }.resume() | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| struct NewsResponse: Codable { | |
| let articles:[Articles]? | |
| let status : String? | |
| let totalResults:Int? | |
| enum CodingKeys: String, CodingKey { | |
| case status | |
| case totalResults | |
| case articles | |
| } | |
| } | |
| struct Articles: Codable, Identifiable { | |
| var id: String? | |
| let author : String? | |
| let title:String? | |
| let description:String? | |
| let url:String? | |
| let urlToImage:String? | |
| let publishedAt:String? | |
| let content:String? | |
| enum CodingKeys: String, CodingKey { | |
| case id | |
| case url | |
| case author | |
| case title | |
| case description | |
| case urlToImage | |
| case publishedAt | |
| case content | |
| } | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| struct QuestionListView:View { | |
| var alrticles:Articles | |
| var body: some View { | |
| VStack(alignment: .leading, spacing: 8) { | |
| HStack(alignment: .top) { | |
| AsyncImage(url: URL(string:alrticles.urlToImage ?? "")) { image in | |
| image.resizable().clipShape(Circle()) | |
| } placeholder: { | |
| Circle().foregroundStyle(.gray) | |
| } | |
| .frame(width: 60, height: 60) | |
| VStack(alignment:.leading, spacing: 6) { | |
| HStack { | |
| Text(alrticles.title ?? "") | |
| .bold() | |
| Spacer() | |
| Text(Date.now.formatted(date: .numeric, time: .omitted)) | |
| .font(.caption) | |
| } | |
| Text(alrticles.description ?? "") | |
| .font(.subheadline) | |
| HStack { | |
| Label("11", systemImage: "text.bubble") | |
| Spacer() | |
| Label("12", systemImage: "chart.bar") | |
| Spacer() | |
| Label("13", systemImage: "eye") | |
| } | |
| .font(.caption) | |
| } | |
| } | |
| } | |
| .padding(.vertical, 6) | |
| } | |
| } | |
| ============== | |
| import SwiftUI | |
| struct QuestionsView: View { | |
| @StateObject var viewModel = QuestionsViewModel() | |
| var body: some View { | |
| NavigationStack { | |
| Group { | |
| List(viewModel.getNews) { news in | |
| QuestionListView(alrticles: news) | |
| } | |
| } | |
| .navigationTitle("Questions") | |
| .alert("Error", isPresented: .constant(false)) { | |
| //Button("No",role: .cancel) {} | |
| //Button("Yes",role: .destructive) {} | |
| Button("Ok",role: .cancel) {} | |
| } message: { | |
| Text("something went wrong") | |
| } | |
| } | |
| } | |
| } | |
| #Preview { | |
| QuestionsView() | |
| } | |
| ================= | |
| import SwiftUI | |
| struct TabBarView: View { | |
| var body: some View { | |
| TabView { | |
| QuestionsView() | |
| .tabItem { | |
| Image("home") | |
| } | |
| SearchView() | |
| .tabItem { | |
| Image(systemName: "magnifyingglass") | |
| } | |
| UsersView() | |
| .tabItem { | |
| Image(systemName: "person.3") | |
| } | |
| } | |
| } | |
| } | |
| #Preview { | |
| TabBarView() | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| @MainActor | |
| final class QuestionsViewModel: ObservableObject { | |
| @Published private(set) var getNews:[Articles] = [] | |
| init() { | |
| self.loadQuestions() | |
| } | |
| } | |
| extension QuestionsViewModel { | |
| func loadQuestions() { | |
| APIService.shared.request(enpoint: APIEndPoint.news.url) { (result: Result<NewsResponse, Error>) in | |
| DispatchQueue.main.async { | |
| switch result { | |
| case .success(let news): | |
| self.getNews = news.articles ?? [] | |
| print(self.getNews as Any) | |
| case .failure(let error): | |
| print("Error: \(error)") | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment