Skip to content

Instantly share code, notes, and snippets.

extension UIImage {
func calcImageRatio() -> CGFloat {
let imageRatio = CGFloat(self.size.width / self.size.height)
return imageRatio
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let currentImage = images[indexPath.row]
let imageRatio = currentImage.calcImageRatio()
func fetchPosts(){
Alamofire.request("https://jsonplaceholder.typicode.com/posts", method: .get, parameters: nil)
.validate(statusCode: 200..<300).responseJSON { response in
guard response.result.error == nil else {
print("error calliing on /posts")
return
}
genericFetch(urlString: "https://jsonplaceholder.typicode.com/comments") { (comments: [Comment]) in
print(comments.forEach({print("\n postId: \($0.postId)\n id: \($0.id)\n name: \($0.name)\n email:\($0.email) body: \($0.body)\n\n")}))
}
struct Comment: Decodable {
var postId: Int
var id: Int
var name: String
var email: String
var body: String
}
genericFetch(urlString: "https://jsonplaceholder.typicode.com/posts") { (posts: [Post]) in
print(posts.forEach({print("title: \($0.title)\n body:\($0.body)\n\n")}))
}
func genericFetch<T: Decodable>(urlString: String, completion: @escaping (T) -> ()) {
Alamofire.request(urlString, method: .get).validate(statusCode: 200..<300).response { response in
guard response.error == nil else {
print("error calliing on \(urlString)")
return
}
guard let data = response.data else {
struct Post: Decodable {
var userId: Int
var id: Int
var title: String
var body: String
}
Post title: This is a POST request
let postsURLEndPoint: String = "https://jsonplaceholder.typicode.com/posts"
let newPost: [String: Any] = ["userId" : 12345, "title": "This is a POST request", "Body": "This reqeust is sent with Alamofire"]
Alamofire.request(postsURLEndPoint, method: .post, parameters: newPost,
encoding: JSONEncoding.default)
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error")
print(response.result.error!)
return
body: quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto