Skip to content

Instantly share code, notes, and snippets.

@vikdenic
Created March 23, 2018 00:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikdenic/2d564e4eb5fd04004352e999456e7895 to your computer and use it in GitHub Desktop.
Save vikdenic/2d564e4eb5fd04004352e999456e7895 to your computer and use it in GitHub Desktop.
Command Line script in Swift
#!/usr/bin/swift
import Foundation
struct Article: Codable {
let title: String
let description: String
}
func foo() {
let urlString = "https://swift.mrgott.pro/blog.json"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else {
print("no data")
return
}
//Implement JSON decoding and parsing
do {
//Decode retrived data with JSONDecoder and assing type of Article object
let articlesData = try JSONDecoder().decode([Article].self, from: data)
//Get back to the main queue
DispatchQueue.main.async {
print(articlesData)
}
} catch let jsonError {
print(jsonError)
}
}.resume()
}
foo()
RunLoop.main.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment