Skip to content

Instantly share code, notes, and snippets.

@kobeumut
Created January 5, 2018 19:01
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save kobeumut/b06015646aa0d5f072bfe14e499690ef to your computer and use it in GitHub Desktop.
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
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()
}
@saroar
Copy link

saroar commented May 16, 2018

what about POST request ?

@nkarishma
Copy link

what about POST request ?

@AdamSanderz
Copy link

why on earth you have put the struct inside the function? :O :O

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment