I’m fond of a site called The Pastry Box Project. It’s a collection of thoughts and stories by a bunch of great writers, but that’s not why I mention it. I mention it because I noticed they had a nice, simple, REST API. Nifty!
PastryKit
Since I really enjoy writing code that communicates with services, and I needed a little project to learn some Swift, I thought I’d write a couple classes, I call PastryKit, that implement the Pastry Box REST API in Swift.
PastryKit is just two classes:
- PastryKit – Allows you to communicate with the Pastry Box REST API.
- Pastry – This is an entry returned by a call to PastryKit.
You can read more about The Pastry Box API on their site.
private func showPastryBaker() { var pastryKit = PastryKit(); pastryKit.thoughtsByBaker("mike-monteiro", completionHandler:{(pasteries, error) in if (nil != error) { println(error) } if (nil != pasteries) { println(pasteries) } }); }
The Heavy Lifting
Most of the “heavy lifting” is performed in one place in PastryKit.swift in the private getWithIngredient function. It makes use of NSURLSession, which was introduced in iOS 7. Go find that function if you’d like to see how to do an HTTP GET in Swift. This is a simple case, it doesn’t require any authentication, or messing around with headers, and it only does GET’s. Doing a POST, PATCH or DELETE would, of course, require some changes, but you get the idea.
/// getWithIngredient - worker method that does all gets private func getWithIngredient(ingredient: String?, completionHandler: (([Pastry]!, NSError!) -> Void)?) { let url = ((ingredient) != nil) ? NSURL(string: PastryBoxUrl + ingredient!) : NSURL(string: PastryBoxUrl) let request = NSURLRequest(URL: url!) let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil) let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler:{(data, response, error) in if (error == nil) { var conversionError: NSError? var ingredientsArray: NSArray = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error:&conversionError) as NSArray if (conversionError == nil) { var pasteries = Pastry.pastryArrayFromNSArray(ingredientsArray) if (completionHandler != nil) { completionHandler!(pasteries, nil) } } else { println(conversionError) if (completionHandler != nil) { completionHandler!(nil, conversionError) } } } else { println(error) if (completionHandler != nil) { completionHandler!(nil, error) } } }); task.resume() }
Go Get It!
The code is available on GitHub if you have need to get stuff from The Pastry Box Project in your Swift or Objective-C app.
Enjoy!