5. HTTP in Swift

GET, GETJSON, POSTJSON

Santosh Rajan
Swift Programming
2 min readJun 23, 2014

--

Previous Posts

  1. Learn Swift by running Scripts
  2. Functional Swift
  3. More Functional Swift
  4. JSON in Swift

In this post we will write some HTTP wrapper functions. The Objective is that you can use them even if you don’t understand Objective-C. The three most useful functions are HTTPGet, HTTPGetJSON, HTTPPostJSON. I will leave it to the readers to write other HTTP functions.

First we create function called HTTPsendRequest. You don’t have to call this function directly. This function is used by our GET and POST requests.

The HTTPGet function takes two parameters. A String url and a callback function. The callback function is called with two parameters when the request is completed. The first parameter is a data String. And the second parameter is a error String optional (you will get the error message as String in case of error).

The last line calls a sleep function for 10 seconds. This is required only if you are running this script from the command line. Because the get request is asynchronous, the program will exit before the callback is called otherwise. You may have to adjust the no of seconds based on your connection speed.

Next we will write HTTPGetJSON. This time the callback will be called with data as Dictionary<String, AnyObject> type. We will use JSONparseDict from the previous post to parse the response.

We then use the HTTPGetJSON to get the top songs from the iTunes JSON api and print the song names.

Next we do HTTPPostJSON. It takes three parameters. A url String. A JSON Object. A callback. Callback works just like the GET callback. The JSON Object is converted to a String using the JSONStringify function from the previous post.

Follow Swift Programming to stay updated on this series.

--

--

Santosh Rajan
Swift Programming

Founder www.geekskool.com. Programmer for over 30 years. Making better programmers is my passion. Bangalore. India. www.santoshrajan.com