Skip to content

Instantly share code, notes, and snippets.

@funmia
Created November 24, 2018 20:21
Show Gist options
  • Save funmia/91cff73f77b527873336a2c91b5ddb44 to your computer and use it in GitHub Desktop.
Save funmia/91cff73f77b527873336a2c91b5ddb44 to your computer and use it in GitHub Desktop.
sample urlsession call using https://jsonplaceholder.typicode.com
struct Todo: Decodable {
    let userId: Int
    let id: Int
    let title: String
    let completed: Bool
}

func getToDoItems(completionHandler: @escaping ([Todo]) -> Void) {

    let endpoint = "https://jsonplaceholder.typicode.com/users/1/todos"

    guard let url = URL(string: endpoint) else {
        print("Invalid url")
        return
    }

    let urlRequest = URLRequest(url: url)
    let session = URLSession(configuration: .default)

    let task = session.dataTask(with: urlRequest) { data, response, error in

        guard error == nil else {
            print("Error\(String(describing: error?.localizedDescription))")
            return
        }

        guard let data = data else {
            print("Error: did not receive data")
            return
        }
        print(String.init(data: data, encoding: .utf8))
        do {
            let decoder = JSONDecoder()

            let items = try decoder.decode([Todo].self, from: data)

            completionHandler(items)
        } catch {
           print("error decoding items")
        }
    }
    task.resume()
}

getToDoItems() { items in
    print(items)
}

PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment