Skip to content

Instantly share code, notes, and snippets.

@azamsharp

azamsharp/ContentView.swift Secret

Created Jun 9, 2021
Embed
What would you like to do?
//
// ContentView.swift
// MoviesApp
//
// Created by Mohammad Azam on 6/9/21.
//
import SwiftUI
struct ContentView: View {
@StateObject private var movieListVM = MovieListViewModel()
var body: some View {
VStack {
Text("Hello, world!")
.padding()
.task {
await movieListVM.fetchAllMovies()
}
Button("Load Data") {
let handler = async {
await movieListVM.fetchAllMovies()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
//
// Movie.swift
// MoviesApp
//
// Created by Mohammad Azam on 6/9/21.
//
import Foundation
struct MovieResponse: Decodable {
let movies: [Movie]
private enum CodingKeys: String, CodingKey {
case movies = "Search"
}
}
struct Movie: Decodable {
let title: String
let imdbId: String
let poster: String
private enum CodingKeys: String, CodingKey {
case title = "Title"
case imdbId = "imdbID"
case poster = "Poster"
}
}
//
// MovieListViewModel.swift
// MoviesApp
//
// Created by Mohammad Azam on 6/9/21.
//
import Foundation
class MovieListViewModel: ObservableObject {
func fetchAllMovies() async {
do {
let _ = try await Webservice().getMovies()
// map the movies to MovieViewModel
// assign the [MovieViewModel] to a @Published property
} catch {
print(error)
}
}
}
//
// Webservice.swift
// MoviesApp
//
// Created by Mohammad Azam on 6/9/21.
//
import Foundation
enum NetworkError: Error {
case badURL
case decodingError
case noData
}
class Webservice {
func getMovies() async throws -> [Movie] {
guard let url = URL(string: "http://www.omdbapi.com/?s=Batman&page=2&apikey=YOURAPIKEY") else {
throw NetworkError.badURL
}
let (data, _) = try await URLSession.shared.data(from: url)
let movieResponse = try? JSONDecoder().decode(MovieResponse.self, from: data)
return movieResponse?.movies ?? []
}
/*
func getMovies(completion: @escaping (Result<[Movie], NetworkError>) -> Void) {
guard let url = URL(string: "http://www.omdbapi.com/?s=Batman&page=2&apikey=564727fa") else {
completion(.failure(.badURL))
return
}
URLSession.shared.dataTask(with: url) { (data, _, error) in
guard let data = data, error == nil else {
completion(.failure(.noData))
return
}
let movieResponse = try? JSONDecoder().decode(MovieResponse.self, from: data)
completion(.success(movieResponse?.movies ?? []))
}.resume()
} */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment