Skip to content

Instantly share code, notes, and snippets.

@gtokman
Last active March 27, 2021 13:06
Show Gist options
  • Select an option

  • Save gtokman/5c039b74b118437cf7214d3c97b0143e to your computer and use it in GitHub Desktop.

Select an option

Save gtokman/5c039b74b118437cf7214d3c97b0143e to your computer and use it in GitHub Desktop.
URLSession + Combine
import UIKit
import Combine
import PlaygroundSupport
let label = UILabel(frame: .init(origin: .zero, size: CGSize(width: 100, height: 100)))
let url = URL(string: "https://api.mocki.io/v1/aebff128")!
var cancellables = Set<AnyCancellable>()
URLSession
.shared
.dataTaskPublisher(for: url) // 1
.map(\.data) // 2
.decode(type: [String: [String]].self, decoder: JSONDecoder()) // 3
.compactMap(\.["results"]) // 4
.replaceError(with: []) // 5
.map { $0.joined(separator: " ") }
.receive(on: DispatchQueue.main) // 6
.assign(to: \.text, on: label) // 7
.store(in: &cancellables) // 8
PlaygroundSupport.PlaygroundPage.current.liveView = label
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment