Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
More essential user interaction topics
- Loading branch information
1 parent
406d04e
commit 84a478a
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// Web API requestor, returns a "Courses" object (or nil) | ||
// This is simple example, and is NOT a best practice | ||
// The function is synchronous and will block the UI | ||
// Students can use this code as-is, | ||
// but it assumes the "package" struct is named "PackageCourses" | ||
func doRequest(url: URL) -> PackageCourses? { | ||
|
||
// A do-catch statement handles errors | ||
// For the following, if there is an error, "catch" returns nil | ||
do { | ||
|
||
// Attempt to get the data from the web API | ||
let data = try Data(contentsOf: url) | ||
|
||
// Create and configure a JSON decoder | ||
let decoder = JSONDecoder() | ||
decoder.dateDecodingStrategy = .iso8601 | ||
|
||
// Attempt to decode the data into a "PackageCourses" object | ||
let result = try decoder.decode(PackageCourses.self, from: data) | ||
|
||
// If it gets this far, it has been successful | ||
return result | ||
} | ||
catch { | ||
// Uh oh, error | ||
print("Request error: \(error.localizedDescription)") | ||
return nil | ||
} | ||
} |