Created
March 23, 2018 00:54
-
-
Save vikdenic/2d564e4eb5fd04004352e999456e7895 to your computer and use it in GitHub Desktop.
Command Line script in Swift
This file contains hidden or 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
#!/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