We can fetch data from the URL in Combine using dataTaskPublisher(for:)
method.
The code looks like this:
import Combine
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let url = URL(string: "https://jsonplaceholder.typicode.com/users/1")!
var cancellables: Set<AnyCancellable> = []
URLSession.shared
.dataTaskPublisher(for: url)
.compactMap { String(data: $0.data, encoding: .utf8) }
.sink { completion in
print(completion)
} receiveValue: { value in
print("\(value)")
}
.store(in: &cancellables)
The output of the code will be the JSON data fetched from the URL.
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
finished