struct Course: Decodable {
let id: Int
let name: String
let imageUrl: String
let number_of_lessons: Int
}
func start() {
fetchCoursesJSON { (res) in
switch res {
case .success(let courses):
courses.forEach({ (course) in
print(course.name)
})
case .failure(let err):
print("failed", err)
}
}
}
func fetchCoursesJSON(completion: @escaping (Result<[Course], Error>) -> ()) {
let urlString = ""
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, resp, err) in
if let err = err {
completion(.failure(err))
return
}
// successful
do {
let courses = try JSONDecoder().decode([Course].self, from: data!)
completion(.success(courses))
} catch let jsonError {
completion(.failure(jsonError))
}
}.resume()
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
List of users who liked
00