Skip to content

Instantly share code, notes, and snippets.

View saoudrizwan's full-sized avatar

Saoud Rizwan saoudrizwan

View GitHub Profile
@saoudrizwan
saoudrizwan / ControllerViewDesignPattern.swift
Created June 1, 2017 14:13
Controller View Design implementation.
import UIKit
class ControllerView: UIView {
weak var controller: Controller?
init(controller: Controller) {
super.init(frame: controller.view.frame)
controller.view.addSubview(self)
self.translatesAutoresizingMaskIntoConstraints = false
class MainController: Controller {
var mainControllerView: MainControllerView {
get {
guard let controllerView = self.controllerView as? MainControllerView else { fatalError("Controller view has not been set") }
return controllerView
}
}
override func viewDidLoad() {
enum Result<Value> {
case success(Value)
case failure(Error)
}
func getPosts(for userId: Int, completion: ((Result<[Post]>) -> Void)?) {
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = "jsonplaceholder.typicode.com"
urlComponents.path = "/posts"
struct Post: Codable {
let userId: Int
let id: Int
let title: String
let body: String
}
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
struct Post: Codable {
let user: Int
let body: String
enum CodingKeys: String, CodingKey {
case user = "userId"
case body
}
}
var posts = [Post]()
func buttonTapped() {
getPosts(for: 1) { (result) in
switch result {
case .success(let posts):
self.posts = posts
case .failure(let error):
fatalError("error: \(error.localizedDescription)")
}
// Helper method to get a URL to the user's documents directory
// see https://developer.apple.com/icloud/documentation/data-storage/index.html
func getDocumentsURL() -> URL {
if let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
return url
} else {
fatalError("Could not retrieve documents directory")
}
}
let myPost = Post(userId: 1, id: 1, title: "Hello World", body: "How are you all today?")
func submitPost(post: Post) {
// ...
}
// We'll need a completion block that returns an error if we run into any problems
func submitPost(post: Post, completion:((Error?) -> Void)?) {
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = "jsonplaceholder.typicode.com"
urlComponents.path = "/posts"
guard let url = urlComponents.url else { fatalError("Could not create URL from components") }
// Specify this request as being a POST method
var request = URLRequest(url: url)