More Asynchronous Data Handling with Swift

In the previous article we saw how to get REST data in Swift using NSURL methods. In this article we shall look further at downloading data.

Using an NSURLRequest

This time instead of using NSURL, we use an NSURLRequest. The method is similar to the way we used NSURL previously.
let url = NSURLRequest(URL: NSURL(string: "http://httpbin.org/ip")!)
NSURLSession.sharedSession().dataTaskWithRequest(url) {
    (data, response, error) -> Void in
        print("Done")
    }

Using Methods to upload / Download

To access additional functionality, we need to use NSMutableURLRequest instead of the NSURLRequest.
let url = NSMutableURLRequest(URL: NSURL(string:"http://httpbin.org/ip")!)

The NSMutableURLRequest has slightly more functionality than NSURL. We can set the methods, which will allow methods like GET, PUT, POST, etc, the default value is GET.
url.HTTPMethod = "PUT"

Adding Headers

When you use PUT or POST and want to send data, you might have JSON formatted data that you send to the server. To send JSON formatted data, you need to set the headers to specify that the data is of type json. You can do that with,

url.setValue("application/json", forHTTPHeaderField: "Content-Type")

you can add more header values as required

Setting Data to POST/PUT

To add any data with a POST/PUT request we can add that to the HTTPBody. One thing to note is that the data added to the HTTPBody is of type NSData. The data of type JSON is basically a Dictionary or an Array of Dictionaries. The task at hand would be to convert that JSON snip into NSData. Also note that while JSON is plain text, it is a dictionary/array in Swift/Obj-C.

let jsonSnip = ["email":"dev@oz-apps.com"]
var theJSON:NSData?
theJSON = try NSJSONSerialization.dataWithJSONObject(theJSONData, options: .PrettyPrinted)

url.HTTPBody = theJSONData

Usage Scenarios

You can use this to post to a website where usernames and passwords or tokens are to be included. It can be set in the data or the headers.

Have fun with this, hope that you can make use of this for some of your projects. Hopefully next time we can look at parsing the JSON received mapping it with a user class manually and/or automatically.

Comments

Popular Posts