Simple API call and printing JSON

I have been trying to learn xcode and swift by example.I have tried tons of examples I searched for, all of which fail in one way or another…usually wrong swift version or syntax. I want to make a very simple app that makes an api call to my personal weather station and prints the json data to a text box or frame on my single view app. I want to learn the details and presentation as I go. I would like to perfect the story board and view as I learn new concepts.

https://api.weather.com/v2/pws/observations/current?stationId=KKSSPRIN16&format=json&units=e&apiKey=221d8fc5255d49a59d8fc5255db9a5fd

I would sure appreciate any guidance you may be able to give

I am running xcode 11 with swift 5.1

hi @taoscowboy,
Welcome to the forums and congrats on your first question.

Getting JSON from a Rest API endpoint is perhaps the most common task, the most straight forward way is to create a structure with the elements in the JSON and make it conform to codable so that it can be processed by Swift when you use the JSONDecoder to decode the data into the object.

The other method is to use JSONSerialization from the data into an Array with the key value pairs.

cheers,

Thanks for taking the time to respond, its not easy being the new guy! I will attempt to locate some specific examples via Google to work from. So far, my attempts at finding examples has been very confusing, to say the least. I have very limited knowledge of programming. My last programming endeavors were in grad school using Fortran 77.

Like Jay said, you need to create structs so you can decode the JSON. I’m fairly new to coding but I’ve been trying to master Networking and parsing JSON so I made the objects you need to get you started. Most of the variables are optionals so you’ll have to deal with that when you use them. Hope this helps.

Thanks for posting this structure, it clears up several things for me. I am reading about Codable and Decodable in Swift as we speak. I did get the basic api call to function and return some data to the console. When I get back to my Mac, I will post the code that I am working with.

Thanks again

1 Like

@taoscowboy Thanks very much for your question!

Here is a screencast from our site that discusses the Codable protocol.

Here is also a link to a tutorial on how to use URLSession for networking in iOS!

I do wish to point out that the concepts you are working on right now are FUNDAMENTAL concepts in iOS development. Networking, connecting a REST API, parsing JSON data asynchronously, and then displaying them in a UITableView in some form are very standard questions that you will be asked at iOS developer job interviews so please make sure you take your time, and learn these concepts THOROUGHLY! :slight_smile:

I hope this helps!

All the best!

This topic was automatically closed after 166 days. New replies are no longer allowed.