Skip to content

Instantly share code, notes, and snippets.

@n1kron
Created October 15, 2017 13:16
Show Gist options
  • Save n1kron/2ac6f2b8d13fc07735b46c8c2664d179 to your computer and use it in GitHub Desktop.
Save n1kron/2ac6f2b8d13fc07735b46c8c2664d179 to your computer and use it in GitHub Desktop.
import UIKit
struct Post : Decodable {
var userId: Int = 1
var id: Int
var title: String
var body: String
}
class PostsViewController: UIViewController, UITextFieldDelegate{
@IBOutlet weak var textView: UITextField!
@IBOutlet weak var body: UILabel!
var n: String? = nil
// func textFieldDidEndEditing(_ textView: UITextField) {
//n = textView.text!
// }
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func acceptButton(_ sender: Any) {
n = textView.text
getDataFromJson()
}
func getDataFromJson () {
let urlString = "https://jsonplaceholder.typicode.com/posts/\(String(describing: n))"
guard let url = URL(string: urlString)else{return}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {return}
guard error == nil else {return}
do{
//декод
let postId = try JSONDecoder().decode(Post.self, from: data)
//adding the name to the array
print(postId)
}catch let error {
print(error)
}
}.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment