Created
January 5, 2018 19:01
-
-
Save kobeumut/b06015646aa0d5f072bfe14e499690ef to your computer and use it in GitHub Desktop.
Simple Fetch Url and Parse Json on Swift 4 with codable and URLSession
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
func fetchResultsFromApi() { | |
struct MyGitHub: Codable { | |
let name: String? | |
let location: String? | |
let followers: Int? | |
let avatarUrl: URL? | |
let repos: Int? | |
private enum CodingKeys: String, CodingKey { | |
case name | |
case location | |
case followers | |
case repos = "public_repos" | |
case avatarUrl = "avatar_url" | |
} | |
} | |
guard let gitUrl = URL(string: "https://api.github.com/users/kobeumut") else { return } | |
URLSession.shared.dataTask(with: gitUrl) { (data, response | |
, error) in | |
guard let data = data else { return } | |
do { | |
let decoder = JSONDecoder() | |
let gitData = try decoder.decode(MyGitHub.self, from: data) | |
print(gitData.name ?? "Empty Name") | |
} catch let err { | |
print("Err", err) | |
} | |
}.resume() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why on earth you have put the struct inside the function? :O :O