LEADER
LEADER

Reputation: 113

Restful application in iOS using Swift

I am new to Swift/iOS programming and I wanted to know how exactly you are supposed to handle web services with a restful method, what to use and what to take into account?

I'm already used to web services, and I can launch services using PHP servers for example, and also used to restful applications meanly in Java applications. I only need to know best framework to manipulate JSON or XML data using iOS Swift.

Upvotes: 2

Views: 813

Answers (1)

Vasil Garov
Vasil Garov

Reputation: 4931

It is really a matter of taste. Personally I prefer using the native libraries where I can. So let's start with the native options.

1. NSURLConnection

You can use it like this:

let url = NSURL(string: "resourceUrl")!
let request = NSURLRequest(URL: url)

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse!, data: NSData!, error: NSError!) in
    if error == nil {
        let results: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil)
        if results != nil {
            //handle the response here
        }
    } else {
        //handle error
    }
}

2. NSURLSession

Introduced in iOS7, this is generally the better approach.

let url = NSURL(string: "resourceUrl")!
let request = NSURLRequest(URL: url)
let urlSession = NSURLSession.sharedSession()
let dataTask = urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if (error == nil) {
            var error : NSError?
            let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
                options: NSJSONReadingOptions.AllowFragments,
                error:&error)

                //handle the response here
    }
}

dataTask.resume()

3. If you want to go with a more sophisticated approach meaning using an external library you can choose Alamofire which can be found here. You can read about its pros vs the standard native approaches.

4. If you are exclusively dealing with JSON then you can go with SwiftyJSON which makes parsing JSON really easy.

Good luck!

Upvotes: 4

Related Questions