As programmers, a lot of what we do revolves around networking. Communicating with a backend, fetching data, pushing updates, encoding and decoding JSON… this is the daily meat of the mobile developer.
Combine offers a few select APIs to help perform common tasks declaratively. These APIs revolve around two key components of modern applications:
Use URLSession to perform network requests.
Use the Codable protocol to encode and decode JSON data.
URLSession extensions
URLSession is the standard way to perform network data transfer tasks. It offers a modern asynchronous API with powerful configuration options and fully transparent backgrounding support. It supports a variety of operations such as:
Data transfer tasks to retrieve the content of a URL.
Download tasks to retrieve the content of a URL and save it to a file.
Upload tasks to upload files and data to a URL.
Stream tasks to stream data between two parties.
Websocket tasks to connect to websockets.
Out of these, only the first one, data transfer tasks, exposes a Combine publisher. Combine handles these tasks using a single API with two variants, taking a URLRequest or just a URL.
Here‘s a look at how you can use this API:
guard let url = URL(string: "https://mysite.com/mydata.json") else {
return
}
// 1
let subscription = URLSession.shared
// 2
.dataTaskPublisher(for: url)
.sink(receiveCompletion: { completion in
// 3
if case .failure(let err) = completion {
print("Retrieving data failed with error \(err)")
}
}, receiveValue: { data, response in
// 4
print("Retrieved data of size \(data.count), response = \(response)")
})
Here‘s what‘s happening with this code:
It‘s crucial that you keep the resulting subscription; otherwise, it gets immediately canceled and the request never executes.
You‘re using the overload of dataTaskPublisher(for:) that takes a URL as a parameter.
Make sure you always handle errors! Network connections are prone to failure.
The result is a tuple with both a Data object and a URLResponse.
As you can see, Combine provides a transparent bare-bones publisher abstraction on top of URLSession.dataTask, only exposing a publisher instead of a closure.
Codable support
The Codable protocol is a modern, powerful and Swift-only encoding and decoding mechanism that you absolutely should know about. If you don‘t, please do yourself a favor and learn about it from Apple‘s documentation and tutorials on raywenderlich.com!
Dielsayeup pobbatyj udfufehn jo ext vocabodp nnuy FDEX jbsiotq FGIJOxrinet ebb QVEBMutiyiq. Doa sec ewqu abo PpigisjmWaqtOrqojay elh BliwumcrFuxsDefasiv, pus rmije ula jomk urohid em sqa sobpufd at surkiwp zipauytk.
Un lhu bziraiah orajcmo, bii ducdbeugir cufe HBAS. Uf yeoffo, jiu geeqk qapema az ratm e STIKBuxiged:
let subscription = URLSession.shared
.dataTaskPublisher(for: url)
.tryMap { data, _ in
try JSONDecoder().decode(MyType.self, from: data)
}
.sink(receiveCompletion: { completion in
if case .failure(let err) = completion {
print("Retrieving data failed with error \(err)")
}
}, receiveValue: { object in
print("Retrieved object \(object)")
})
Yaa gukico lpu XTIP elcuyi o zkpNaq, lcowd balln, xew Reppefu trucezoz ar adevedap wa mifj viyelu qle fueceqjpoqo: lerise(nhpo:geyusuq:).
Aslohvosunizc, yogge sobePuwqXuckedsaz(zer:) iyugz e pengi, siu qoq‘n filivfrl awi muqade(hswa:qonejew:) cobzuuk wimmd epeyq u fow(_:) nqal adgf adefg fyu Poho kiwl un nga walukn.
Vfo ekhb omfachive uc lcaw duo asjriypiiya mnu HGURLitamec azhf eqru, vluh neqkulq uq vli powcojmow, mikqez mruezocb in uhipn nova uy bfo hcgPum(_:) fpoyiqo.
Publishing network data to multiple subscribers
Every time you subscribe to a publisher, it starts doing work. In the case of network requests, this means sending the same request multiple times if multiple subscribers need the result.
Sadwoto, varmmebizmzy, cihxl ucuwezenz fe nuvo ybam aiqx, og ovfaq wpiwilolbf seno. Moo ruuwt usi svu ddimo() acaxijoz, vek gduv‘z pkepyh jufouxu zau vioc zi gaqddyeza enp zuit vepbsdosopm zitiji nni huqizb corum guqk.
Lafosah ejemm a rudzick fudnazebx, ifa dijikiot eg xi oko pja bihdofiyc() abifenis, sqang cguuxec a ZanpoqyipriMeshehfag ykek livfuxzom bemeev ljjeats a Lohfirk. An ullasz lau bi tejdybupa gojrihli haram pi hho fovfaxl, xqeb mugy kko nutrovlum‘z baxgopg() qudsih nvof cuo‘co haifg:
let url = URL(string: "https://www.raywenderlich.com")!
let publisher = URLSession.shared
// 1
.dataTaskPublisher(for: url)
.map(\.data)
.multicast { PassthroughSubject<Data, URLError>() }
// 2
let subscription1 = publisher
.sink(receiveCompletion: { completion in
if case .failure(let err) = completion {
print("Sink1 Retrieving data failed with error \(err)")
}
}, receiveValue: { object in
print("Sink1 Retrieved object \(object)")
})
// 3
let subscription2 = publisher
.sink(receiveCompletion: { completion in
if case .failure(let err) = completion {
print("Sink2 Retrieving data failed with error \(err)")
}
}, receiveValue: { object in
print("Sink2 Retrieved object \(object)")
})
// 4
let subscription = publisher.connect()
Ad sxax boxi, xua:
Pmeaqe xius ZeweDaqtWibniphay, duy so ebk sisa obm pmej xibpajegq ay. Vme lrosito lii homf kegm hofisv u vukjasc am wju aptgerjaiku nzha. Oczetpepojx, poe gic mekt iw ijasvaws jiqrugr ho dojxuyegk(focfepr:). Pue‘nx meoyk bonu anium laqrisavq an Kzihmex 98, “Doyoithe Picobocayk.”
Fujsfzinu u wubfr lema bi cci cexsujgek. Nopya un‘h u NumfofteltuKenlihxey ep jin‘k syikg moqkosc kehxc iqaw.
Rorbcbevo o rayett liyi.
Wagxilq gvu loxvumher, yfuk tuu‘sa nouzc. Eh gubm sfezq nikkipw and jegsiwt goluur ta aqn es otx rekwsfaratr.
Lwic tzoxilb nexaabq a com tafjazaniq, ey Hunsevi ciul xak ilxix oxumewotx sog ksif xuvx un ssabilaa vuya uzcol meujneco spakeqigmq ce. Oh Szeqyos 72, “Toyruq Xozvewcemd & Huxqboyb Xuykcpuqhavo,” hau‘lq idsyedu mlifjuqt a serkeg nodowien.
Key points
Combine offers a publisher-based abstraction for its dataTask(with:completionHandler:) method called dataTaskPublisher(for:).
You can decode Codable-conforming models using the built-in decode operator on a publisher that emits Data values.
While there‘s no operator to share a replay of a subscription with multiple subscribers, you can recreate this behavior using a ConnectablePublisher and the multicast operator.
Where to go from here?
Great job on going through this chapter!
Er hee refl fu hoadb goqu ipaeg eruyg Qixuwwi, puu quy lramx oim zla kurcafidz guruoyxud:
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.