5. HTTP in Swift

GET, GETJSON, POSTJSON


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.

import Foundation
func HTTPsendRequest(request: NSMutableURLRequest,
callback: (String, String?) -> Void) {
    let task = NSURLSession.sharedSession()
.dataTaskWithRequest(request) {
(data, response, error) -> Void in
if error {
callback(“”, error.localizedDescription)
} else {
callback(NSString(data: data,
encoding: NSUTF8StringEncoding), nil)
}
}

task.resume()
}
func HTTPGet(url: String, callback: (String, String?) -> Void) {
var request = NSMutableURLRequest(URL: NSURL(string: url))
HTTPsendRequest(request, callback)
}
HTTPGet(“http://www.google.com") {
(data: String, error: String?) -> Void in
if error {
println(error)
} else {
println(data)
}
}
sleep(10)

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 popular posts from the Youtube JSON api and print the title names.

func JSONParseDict(jsonString:String) -> Dictionary<String, AnyObject> {
var e: NSError?
var data: NSData = jsonString.dataUsingEncoding(
NSUTF8StringEncoding)
var jsonObj = NSJSONSerialization.JSONObjectWithData(
data,
options: NSJSONReadingOptions(0),
error: &e) as Dictionary<String, AnyObject>
if e {
return Dictionary<String, AnyObject>()
} else {
return jsonObj
}
}
func HTTPGetJSON(
url: String,
callback: (Dictionary<String, AnyObject>, String?) -> Void) {
    var request = NSMutableURLRequest(URL: NSURL(string: url))
request.setValue(“application/json”, forHTTPHeaderField: “Accept”)
HTTPsendRequest(request) {
(data: String, error: String?) -> Void in
if error {
callback(Dictionary<String, AnyObject>(), error)
} else {
var jsonObj = JSONParseDict(data)
callback(jsonObj, nil)
}
}
}
HTTPGetJSON(“http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2&alt=json") {
(data: Dictionary<String, AnyObject>, error: String?) -> Void in
if error {
println(error)
} else {
if let feed = data[“feed”] as? NSDictionary {
if let entries = feed[“entry”] as? NSArray {
for elem: AnyObject in entries {
let dict = elem as NSDictionary
if let titledict = dict[“title”] as? NSDictionary {
if let title = titledict[“$t”] as? NSString {
println(title)
}
}
}
}
}
}
}

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.

func HTTPPostJSON(url: String,
jsonObj: AnyObject,
callback: (String, String?) -> Void) {
    var request = NSMutableURLRequest(URL: NSURL(string: url))
request.HTTPMethod = “POST”
request.addValue(“application/json”,
forHTTPHeaderField: “Content-Type”)
let jsonString = JSONStringify(jsonObj)
let data: NSData = jsonString.dataUsingEncoding(
NSUTF8StringEncoding)
request.HTTPBody = data
HTTPsendRequest(request, callback)
}

Follow Swift Programming to stay updated on this series.

Email me when Swift Programming publishes stories