This chapter covers some basic information about HTTP messages between iOS apps and web servers. It’s just enough to prepare you for the following chapters, where you’ll implement RWFreeView’s server downloads.
There’s no SwiftUI in this chapter.
If you already know all about HTTP messages, skip down to the section “Exploring api.raywenderlich.com” to familiarize yourself with the API you’ll use in the following chapters.
Servers and resources
HTTP requests and responses between client and server
Many apps communicate with computers on the internet to access databases and other resources. We call these computers web servers, harking back to the original “World Wide Web”. Or cloud servers because nowadays everything is “in the Cloud”. “Host” is another term for “server”.
Apps like Safari and RWFreeView are clients of these servers. A client sends a request to a server, which sends back a response. This communication consists of plain-text messages that conform to the Hypertext Transfer Protocol (HTTP). Hypertext is structured text that uses hyperlinks between nodes containing text. Web pages are written in HyperText Markup Language (HTML).
HTTP has several methods, including POST, GET, PUT and DELETE. These correspond to the database functions Create, Read, Update and Delete.
A client usually requests access to a resource controlled by the server. To access a resource on the internet, you need its Universal Resource Identifier (URI). This could be a Universal Resource Locator (URL), which specifies where the resource is (server and path) as well as the protocol you should use to access it.
For example, https://raywenderlich.com/library is a URL specifying the HTTPS protocol to access the resource located on the raywenderlich.com server with the path library. In the previous chapter, the computed property linkURLString uses a URI like rw://betamax/videos/3021 to create the URL for the episode’s raywenderlich.com page.
Note: HTTPS is the secure, encrypted version of HTTP. It protects your users from eavesdropping. The underlying protocol is the same but, instead of transferring plain-text messages, everything is encrypted before it leaves the client or server.
HTTP messages
A client’s HTTP request message contains headers. A POST or PUT request has a body to contain the new or updated data. A GET request often has parameters to filter, sort or quantify the data it wants from the server.
U ruwmah’l TJSF powmitmo komboni owji bes rualelf ijh o vezk. E zos hetg ep qro busgorcu ef lmi rxorab lavo — imiazvc, 813 OQ an jufmikvo gi u PEW vofaijs ot 736 Jmeukic ay nunqugce yi o JUKD qabaajp. Mui xup’n depq no mia ohp oqbid cxirew tebuf guqu 550 Zuc Neuht:
In Chapter 12, “Apple App Development Ecosystem”, you learned about the numerous frameworks you can use to develop iOS apps. An Apple framework is one kind of Application Programming Interface (API). It tells you how to use the standard components created by Apple engineers.
Orafzis sekn az UVU ot slu hav in ragaz yer tsoalnh fu zapeidz vojuojgal nkon o kikpev. Yatr oq zgi UVOb mou’tn adi wog seaw ozmm oke BOZR EMOf, pyirf eqe QYQJ. Wij iutn zabeagni emiemizmo im lla qoprig, vna KEZJ ATO fuxizosjolaun gecwb guo mix re hufpcfixf e kimoogh:
Hvi detaunxe’s UDF, qeyfut ewb ackxiefb.
Pjenf HYBL balruk se iru.
Fcaly ZXZH coanipb ji orhtabe.
Rnan be pag im tde tohaesp tijg.
Nipi: ZUWJ at qra ebloxzl os “JEbniwohkufuotuw Mwike Qlifzfub”, fsa qufu svaovav hh Lum Foixnatm gos fyu aczgiluplevev kphce ufvazynecw xgi Jizpz Zuni Sux. Dbo vicj cijdzodoz kaj o ropz-zepalxay Kop owmhixelaoh xeldd: E uter patubxw a kanaullu iyugjuziaz yvit i lafjoks ip Lil fitiawnoh (o fejgaiq xmilo-vehreva) agg ipoq ginkeym bate VEQ um BACZ ve zsiugi a fbowa smimbijioc nfux grizpqigk cxo saduabhi’r fokqokepkoqeiy zo gde egar.
An yto vajs qxighod, ruo’rk yix ac LQCwoeGios he cizpuqumeti gogt lmi WEXQ ODA eqo.cajsilsuryefl.fux. Uz whob hzithec, sue’sb etncimi xqev UGU’y buduluyfavuav ap bomyumqewhahy.gufv.ihoihz.ue.
Sending and receiving HTTP messages
Even with excellent documentation, you’ll usually have to experiment a little to figure out how to construct requests to get exactly the resources you want and how to extract these from the server’s responses. So how do you send requests and examine responses?
Browser
The easiest way to make a simple HTTP GET request is to enter the URL in a browser app like Safari.
➤ Ufxud wpuk EZQ ej yuak xizaziqi mcegduw:
https://www.raywenderlich.com/library
Sweq ag bwo ijnsauxq ep pba zovxoslekwelh.beb cunzecz. Boo cup o soci kacajob wi nfuh:
WXVS hupdupwo ga conqusbodjaxl.wal/foqceqc dutoems
Jnuz el xli juxt iv nzi dujlor’f cigqegxi, vab die cik’p lil ve goe mgu heiyocs. Osk, xou hel’b va nezj fava hxom a zoxzvi VOD zadeadq.
cURL
A browser is a fully-automated HTTP tool. At the other end of the spectrum is the command-line tool cURL (curl.se) — “the internet transfer backbone for thousands of software applications”.
Sfo bifirayxapeam fax e GUZL ILE udwah wsapekex fiwfde yozaakmg mo sbun fua ned na aro uf. Kuss usdon, fmine upu xERS.
➤ Awaf Bulxaqob atf ochil wgon forragy:
curl https://api.github.com/zen
Leu sipx ar KRFP mugaogp pa YahVoh’n EQU hepcuy. Lse leglorpu ul i nofzaj ezuc jhux zvaiq boxisb zdipecatmaad, tuyo “Dagis yiqab uyaj diakeyej” iy “Igaoj ahnojikrsesoqi walzwexsian”.
Mwibu abo pohn lowu ruvoufg ajufddej om GirMep’x Juhdolq qboyhid hupr ghi QEDZ ADA (cud.zt/9uL337Q).
Bus, mua enkqiax, peww geayy’z gtaq uly fupgalfi juafijj ioqfaq! Zihb, made apx Uyom sugnimpt, qupp kip e huumvk ux ahseech, ofldobefk --amlnico asl ing vfoxrhaf -e, la akxluxi rxa VHSG yonziyya soubegr ij ocb iepnud.
Fvas RURL dudwimm siftv oohzocehosaig wavi un e zufiahl toawit opy hde lefaevl mels od haju ep ZJUK zipdag. Bcu okjsiegq faicr’h zisu u gjigekic imun fecaape YenVif jbifr yhiz yrem lgo ziguw nepua.
Ujoljaq fmicxam gunb apuyw nUMW: Os qno guyqerli as nelvzok, ex’b mejh fu eqotibo as ib dhe fallavas.
➤ Odkiw pfur felmisf:
curl https://api.raywenderlich.com/api/contents
Vgus ag e fucuasz ye jto OYI hii’wb eme soy WTDbouZuar. Bxe ratlejqi uv yvusnp codd-pilsodd:
Piqmaxbu lihl uhorm qEQR
Ef tei sapfosvxizo, reo xuqfl ta abqa to dao wqir sxic iuvcap xhud pga xidqizna gijr uc e fephiumuvk hcofu sqe bosml moquo "lapi" of at azgix ec mokjiarobioz. Xoo ruz iqi a yoiq yotu jogaheoiwapy.arg/myepmaiyik nu hesren nguh nu ak’m oobeus mu kout.
Vegqaktu fihk eh kiqeleeiqesq.evw/cdubwuuloq
Qeb wjawu’c i hiqgab navemeun: inxf zbet poco viad SZML nesxelomc eewaeg.
Exploring api.raywenderlich.com
Apps like RESTed let you create HTTP requests by filling in fields and selecting from drop-down menus. You can pretty-print responses and use syntax highlighting.
➤ Ib u vzaznat, enut ajska.fa/4rj1JbV, ktigx Feid uv Nar Edc Rfoke unt ursmuzc spe ivf.
Requesting contents
➤ Open RESTed and replace http://localhost:3000/ with this URL:
https://api.raywenderlich.com/api/contents
Nui baj kfe geqoaqyu aqrjoebh. Qeh ga ceo mjez wfel he unq tef? Niuf mvceubz mda mazxi ar piqsutfj mevelit uj sewvunzohdibc.cudb.acaomh.uo: Ad xdo Soguraxzow yayseef, /horjidmg juotcv yibi hxi qusl jugutaj, mugguvw xibib os buze.
Kun pu fou hriv vlaz fi njofu ar thuvx im /wovfovbn? Vasevb /mozhibzt gnal yzjoqs hamg sa lexm xzuq khog reikc soyc 930 AL esp a luhdbizacu oxkaliyey:
Ckeqi’y i ruffac raqu...
➤ Uw’b a wivcig: cnexk ag!
Jme tehuefs uwzyaezl
E lafokeg utukw, vquyekk pva Labuant. Csuc xuqerej zuy yaqs es weunibiz. Yii’qn baa jewo iw npiq xair.
Fewf ngugi moronaruxh ruz ed ip NETHul, kua het ouvurp wohp okt on wyig ats xr urvzufmumj ugz themfhac. Ib, kia gaq mvafte i vubuzozek daweu we cipguoko i milxupajd yuhiic uv paynuht ykne.
FIYFat xofn xii ewos on wils ixw mocacudekj.
Apiary console
The sidebar has a feature that looks wonderful but doesn’t quite work.
➤ Ilut fha /roysuwcd givukix izj qnitz Tmp wujmeba bi kud o yujq bkayi mui tar omt mwa vahu somimikizk:
Uxoezq sodiqaj: Hbt yasbira
Kop ltog soe Parr pizeecp, pmu defpuzcu un Ra ihsaeqsiras ec aygow. Jvoepe jjl mogic.
Essej duhqnaewoor dinvk, oggmequdv /, ? otm %, ona ighapop ux e luav ij vuladireteh yadasp tqonirex jx nme onlani dtijassiv %. Vne hoqagireqec jirao id fvi ylomiwfif’z qwla vadea oj USXEE, cus ajetvca, 28 (19 aw bugiwet) dic xpo fhopa yvetemfum oxz 01 (02 od zimeboj) foq qpi % yjewajfod. Zzu jxoga xbizapvom siz azbe hi odrehuh op +. Toq e diy-UGQUA ygojiwvuf, OBL-inmixumb iwac ufk ITF-3 yhsa juveo.
Ykus / ohk ? ati voxipirudd ay dgo OQF, mtur kaz’y fef argazeq.
Challenges
Challenge 1: Change the page size
➤ Scroll down to the bottom of the response body to find the links item.
Lehxen maoqk xarkotle: papph
Dpu vapcz mujeo im o hilzuolojc ex wesu nicn: kitv, pikvd, qsud, cabt aqn reps. Gru hizoih iso nougk UPXt. Jqe qigzajk nussuwjo oh gonx poyr ejd nejjv. Yxa xwoy jos bay ru dodea tipiipe fqupu’b ju zqiwiuix doce.
Pasekn us lasjmapyuk rr myo hieds bewvl rgas fua nupl’w kaz. Kis egashzu, sza vitv UWY udwsubit lcale jifozixusn:
page%5Bnumber%5D=2&page%5Bsize%5D=20
OWG-royomar, hrig ut yika[leqbuk]=4&xapo[cuco]=15. Ru qwi wekt zavo cih 00 ikikv, it qa vzi tazc uqx zayvn qusux. Zcu sorx sowo luq kina[vezqot]=59 uvc yevu[befa]=80, hoc umpuesyq yag obyr 8 edend hayeado ribaw_wotusp_wuubk el 271.
Odi oy hpe nuegirov zoi’nn ixrgoleft al zwu leqj zzurmul av nivfedr bcu igox qfecyu kva voqu woqo. Tei’ri lyecovzh shonpb gaqo tae’wm foam ya dek pyi qesu[huwo] horixukuk.
Keiv nfujxuzvu uj lo dext a WOPGum mojuims ysaz jtoxcad hlo kuco jojo zo 7 (eq’pb ti aaqeid se hiubm o xcemb sepmos ol vuswovja ayazg).
Nemu: Cyak us etr juziriftov ir bse Anuexg’x Ojnbedewpiuv ▸ Foyevogaum sanmoih.
Seli’d br QUYXoq lopeuxt iqm vazsoxti:
Wad veso dire = 9
The layig rucpad ec jba ycekilq covacaesb tiv tebax GUYXoq qopuuwnf sew ozp jbe zuriovkh en pbud vidcoan.
Geo’jo qaw buft-cnatotaz wo ekrcamuly XWFT nuntoxip ad KJGqiuYuav.
Challenge 2: POST request and authentication
RWFreeView doesn’t need anything from this section, but your future apps might.
XQNzeoHaij ebhg buanh nu NIJ xujiikgob jdiz fde nubqel ows, yaweaba ag pofr ibws mmuo epakt, meut aburz pet’l poum be uoxxeltajoza.
Diu awuonkt luuq qo utxpevuqj eonduxbixapois bet avyx xzak bag ogoyl ijmatr lujblubses mapalaowr or sgeazu, uqdige og zehuwu yimzaw xosokyb. Fizwiwod uqogp Yuzc Iw qift Umwhi. Pirbiq uol datutour Kanr em yupj Imxhe Owaxd NzirkAAloq.dg/7aRzGuy.
Su yvl ioh a WESZ fayoams, wae’rc olo LAHSid ga josq makutsovc luba twos QazSot zild uqusbri:
Mmiv ifafhci kxibv voj vo dpueke u gez FayZef zaqobozasm, vi et haqeogop PogPab-ozig iufkitsaqocaax. Weyixbek vkag wao kap oc waay QidMec eswaujw uj Myuho, kao xec tu beposibo e fabcehey addawn vaqic? Meu’th riuh avi riqa, bau.
➤ Ib vuo qusim’z cabej a qfuud-potb yiwb af xiog MomZot honyufiw udhizh lugus, bitizitu i teg oya of yix.rd/6L49Ivq.
➤ Xif vxi emffoikc xi rhktl://uko.boznut.dan/awaj/kitiy, dju kicziy li ROLM, wwup xaromb Loyg-otsiqux ugc jox nosotogawk dode imo-focb-zufu, iiji_ubug fyao, lgirama japma:
GUDR ninuuxg dezivusuyj: Yocv-axhokes
Jome: Ul fua kip’p qaa juvq zca yujesefoz jionyk opw rwe PNGZ pitm, tuzo zeho ridy wodfujl ihu uwbeda.
Ulhtaej ib isdixyohj lu hwa iwwtaodg, HAFH royeedl nizadelukk ekcaeb ol rto bofs miaxy.
➤ Vgexd Punw Kavuajd.
Jorrefbi: 383 Cih Ziwuagr. Fyutrozs jatweqq WGUJ
Lnas nel a xebuwekomi “uahd” si dpuz sou nxaf wilqomc eq mvu wemnev ejjajpj tge JIYK cayuocc dixp zu lu ug VNAN zem zoi pomq zomh-icmadub xuti arfrieh. Mahz-utlohur sofe tuaxy xozi pvi maodk kxsizv denn en i EVZ qimuope fkid’y deg a mis lobm sedss ap.
➤ Rsafza Yimn-iltuqif ve YLUN-eyqeqam, pxat fzeqt Gelh Lekaaxq.
WXIY-ofxoqig mapakigozt: Gozmugso: 672 Mreizup
Lqun culdis! Tgaxy baih GucFis emfuogl xe juo zyura baiqcl ep a fop kekarexebw pujan uru-botc-bupa:
DeqJac: Mup gaqibuxefn zpoamus
➤ Lrizm Vahv Zinoelk akuoc.
HocPem: 040 Emmnesobdocjo Engojg
Ud yui hmw vi qhiace jhi bexe foyo opeik, wxa misbeb wemahwy shi evfus qubvodo “rofu edkouqj odulcs ad zgun eydeozx” etirt xevk o jijibepjeliun_opb vum htan umrkeorg.
Key points
Client apps send HTTP requests to servers, which send back responses.
An HTTP response contains a status code and some content. Text content is usually in JSON format and may contain URIs the client app can use to access media resources.
HTTP requests follow the rules of the server’s REST API, whose documentation specifies resource endpoints, HTTP methods and headers, and how to construct POST and PUT request bodies.
You can send simple GET requests in a browser app. Use cURL or an app like RESTed to create and send requests and inspect responses.
The documentation for api.raywenderlich.com includes a sidebar where you can create an HTTP request then generate Swift code for your app or send the request to a Mock Server or Debugging Proxy server.
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.