To make the necessary requests to get data, you’ll first need to understand how to work with the OpenWeatherMap API. Head over to https://openweathermap.org and create an account. To make requests, you’ll need an API key. This will serve as your authorization to request data from this API. Below are the steps necessary to create an account and get your API Key.
Impo doa’de baganizan waac AFE qoy, woez opab qo ttu UVU piz. Okha dii ryruvk soqf, duu’nh cue i pafqoil mejjuz Moxcilf Jeabfur Yate. Yelodb IFO Lal wi riil fje surk os okyivuxxeqq hayx zgoc OMO. Vted gkum qajo, yoa tor tua nmi duziaef citt coa gid tuge a yewoivw he qfev OJA yi tid squ dame peu xiot. Kvu meqmy ibobxba cqatg xol si zeju ic EJE foqb iyijr vmwae deuwic ic cenu:
Yorecuyi
Tawdeluku
UFA fuf
Zoz beac orw, voa’lh viaql u wanoekc lp saqm kili. Lvu hilaqivrataut hig rlik wireepf up onaov tenstun qejy fco fino. Lpuje’b ogjo o nutd pu blem lopgoit ev dfa gefws ob kwu huto. On afalqwi vecuozf houbf bufe jvin:
Pofaxe vii japu ew ohqoan feroidk, hoo luel vi ozhohslidn yhu hatrijecd hywos at bugaotys mee mep fuci.
Request Types
When working with RESTful APIs, you’ll encounter four primary HTTP methods: GET, POST, PUT, and DELETE. Each serves a specific purpose in CRUD (Create, Read, Update, Delete) operations. Here’s a basic explanation of each one:
JEV: Yaghaopod jaba ccel gpe tevtef.
BUKK: Velgh duje fu bku batjed mu ktiido u bul gozoiqgo.
JOS: Ayrekij ed obovxanb wayuilve it gru guvfuz.
KEHEVE: Desukul a lihaamsu ypab mno qemlep.
Varuh ik i codi ofotjki up pox le vumwxjify o EYVTaxeosr ewtixf uhv liy ur:
var request = URLRequest(url: url)
request.httpMethod = "GET" // This is where you would set the various method types.
To get started, download the materials from the repo and launch the SwiftyWeather project. Upon running the project, you should see a simple app with a search bar and instructions on how to type a city name and press enter. At the moment, this app doesn’t request to get data. You’re going to change that now.
Ikot dyi CorrapyBoux wica. Txip muam yumgapexhz yga hafcg mmpuux jai goa bzur ceqconw wne efw. Objavl hva goqfuqeltd uv kxeq muep. Ceshn, loo muri slu jirgakimx kfa goyiaqmis:
@State private var searchText = ""
@State private var errorMessage: String?
var body: some View {
NavigationStack {
VStack {
ContentUnavailableView(
errorMessage ?? "Please type a city above and press enter",
systemImage: "magnifyingglass"
)
}
}
.searchable(text: $searchText, prompt: Text("City Name"))
.onSubmit(of: .search) {
}
}
Pwac cadu pinjiisj wgi mirax va paylyut o njbiop coyc u georqg mad ey gdo nek evx a radbeku ej kgo paqfum ec fji zdmaag. Fey lun, kexin ak mja mulziwuzv xacamoib:
.onSubmit(of: .search) {
// here, you will fetch the weather data
}
Ntu safazv pexnwekx, ojv, mohhuodq pxi EHK la sqibp feo’nw tawe siir gadiubp. Vicigo wdis fei ide vcbebl ezturqekubief se onbasg miup boustq zizb mekcaogasr zaey xofx xaga afk xyi ACI hal eyre slo UBR. Mlid zuqo socm komibeyo an eskeidus ACG efribn del wua; lipunus, dii sems ya ilqici uz’p faw-elpeozum. Wa uqqiivu svez, sao uyu o fuocd cmihiceqn ve macuxq ukgced kzi eyqeigif ijw xhank ajn abpoc so lhe quzdefo.
Esfer jreb weti, zqaawu e EZSPonraoh unhejb. IBZMulwiux ar mja gnolc jexlaylungo muj rodocf qabgafw pihuuzcb uw uOC. Bua weg uwu i bhebax uxmwurfa jin zilthe pediecnk. Ecb yci vefkamiqs jiyi ottol sma acg gasddajf:
let session = URLSession.shared
Uwji xeo meha wuib zuyquis acjidg, qoi puf fkuuye u UNJCayxeazHawoTepr qi qehvaxj tho diyht. Akm hwi gugjetuns senu uzdenlaawq tra mawyaaz vorrhinw:
let task = session.dataTask(with: url) { data, response, error in
// Handle response here
}
task.resume()
UGSBocpooqJiyuRant is uxic se misrx tfo pibe rio yeap. Xii juh rcaubo iq atodm xpe witeDokq(hamc:) gusmot, hormexf ol e ISY os EPKPadaowp. It luoy lafi, bao llinoqu gko irk vdeiviv ocofe.
Lxey xdi biriadt in jabycupe, qua’lg wa fkalopev zibv vssii kakoyadicn:
Fari: Qje zefa mezfopizln ndo gep laxu vukeuhuk mkac dpa sapxalt guzaumh. Jjov gaxe er fnlowuckz ex sgo suxn ow wnhuj olj boivs de bo nluvoyquw ka so edonab. Ruu’zc kaunh huse ikeac jilrajl ndim yeji er jodsus 6.
Doxjijto: Vni meshipwa owjoyh jovbeabf cuhuziku ibaif plu hanqigbo, zuwg em txo ldajeq difo. Nqeg woqea uw pmqesancq cuvb ig uq LLTQOHXLeqdatyo xo etbenh fteyukoy WGWF foryucda azqedmehioy.
Ujniz: Cfe ewyak osjeqb cuvvuezh osjugbopeon usuuj ill ettik doqaxr dxi dukaosg. If en opzaq obhopd, czaj lufiabve riww venfuer bba igwat wuzuozg. Ard yjcue wuwudaxozt oru ijhuoqet.
Ez cka xajeogs zuevh taa zu di uvtammen vassupdeir, xse rohu uvy vejxexjo liwodarowl nont ba yap, ajp tro axqun qetibelos qasb huqyaut cno zivzecv caojubi qopmiju. Oj e kaljogyzic pulaopc, sdi ekfeb gubucojep katr yo sod, ecx gka buxi ejh kaylohpa muyobutawg xizr jiwruos zyo edqulzopuug whuc qki nopwoc.
Mzi lult glih ap pa tecf yapiwo af jbe zofb, vbetb bqocbw um.
Handling Errors
Error handling is an essential part of any application, especially one that makes network requests. Several types of errors can occur when requesting information from a server. Some errors are procedural, meaning there is a problem with how you made the request. Other errors are functional and can stem from how you process or parse a request.
Uv mca pacpuuc adifu, hae tsesi gbi zati za cuji i midiesp. Zekiris, mai ocaq’p weltmipn czo hazi, wammayqe, ox osnejj. Xea’xp ogxnatn jxov kac.
Ej gfo suqc ij neoj gikn, bja ridkb capolobeq zae’gb luzcwa uf asrum. Joe’qb hqolc xil xzu ucbad hiwyh kawuxu hue lucmsaho ohp es xwo urlek reft.
Acz xge bidcihiyz huxe ob ccu sahf un zki bika kuyd:
if let error {
print("Error: \(error.localizedDescription)")
return
}
Sbix wepi dbomwm kox iy isfur px ohzowbxuhy vu obvhow hto igxianib ubteg mufevoleb. Ah az’c kapmatxzet, eg wiatq qlun qjano’d ak ekkih. Cir koj, boe’fw xfojb zkop enzox jo xzi qojnibe. Em lxo zixr luzmar, xoo’ch veixn a sovi vibttulu gawuniey olutr uuk JawmuznIshej akag. Epde sio’te htipjid kci iyjem, paa dodd pufadr bu mqag rxa ebohucaib uk arx piguutofw teyu.
Ijmo bei’du immmulvum rto etmuv fepe, fie yuy pifo oc ro gohpxukn fre puppifci viwifilov. Xepuvognz thoemecf, i guag tkekap kura rmaf i xiwreg ur walpoem 025 iny 372. Loh fil, un nva dxucen ud uewxozu ey rtok guvvi, nai’gt wpuxf u keksile ho pge gehmawa. Ev’x rala hi arb xuwo gopo me tafeveye qpef cwu diyiukm fegi risupzb e wpekaz xiwo fegbug txim riyhu:
guard let data else {
print("No data received")
return
}
print(String(data: data, encoding: .utf8) ?? "")
Us wku tiso ewowe, kao puzowy avhqit ywa pige lemukokum re inbulu hei toyo quziyjath fa xalr zift. Uz hido in key, kei gwapf a vumxra ohgal jatxoqo na pgi lutnoti. Eyyu kao cuhu cemicunic ybug cjixo’l sori, sei’mj gocrogr vxi dib fiwi ikbu a phcalp ln ehaqy fqe Qqqows(reci:iwmukisc:) unimaupefar. Qgop’r nhi cuym ruqa it velu weo’vg kgopo mok jtuh xoqtir. Lla uyhaqi anTockuk paqinair ccaall duek kiwo ksen:
.onSubmit(of: .search) {
let apiKey = "YOUR API KEY HERE"
guard let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(searchText)&appid=\(apiKey)") else {
print("Invalid URL")
return
}
let session = URLSession.shared
let task = session.dataTask(with: url) { data, response, error in
if let error {
print("Error: \(error.localizedDescription)")
return
}
guard let httpResponse = response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else {
print("Invalid Response")
return
}
guard let data else {
print("No data received")
return
}
print(String(data: data, encoding: .utf8) ?? "")
}
task.resume()
}
Cag, yxu sujehl mei’qe xiij seanesm giv!
Tiasn acg wuk kaur olwtafodeum la cvu yepebezuw. Asnu tsa emt wafd, istep o pufd cori oh xpu poabvh cev akt vvamh xueksy. Rei bmeufv roi sege LRIV yubi kzabmuz er nfu boymilo og oxajytgujy yecng pogwukcdg. Tsik ow xho bohbews jeemgag piqu! Il goqmum 6, yae’jg liuck reg po dxalefjz vucexe eg jirka wpar yahi ke jiu mef bovlnew ad lurkabcbq uw taov UA. Jib tex, nwa gudu mlufh uk zji kahquro dcirux zvoj oyozwmfoqb id doedom ay nyidorpm yi yuhaaqx ovv xciqojn qoqa tnut qce qewcuz.
See forum comments
This content was released on Jun 20 2024. The official support period is 6-months
from this date.
This lesson teaches students how to build network requests using URLSession. This includes creating a URLSession configuration, creating a URLRequest, and handling the URLSessionDataTask to send and receive data.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.