Fork me on GitHub

An Introduction to HTTP

We've covered the building blocks of UI on iOS, but most of the time we want to populate our interface with some data from a server. The Apple-prescribed method of doing this is to use NSURLConnection, which is a very powerful but verbose class for sending HTTP requests; instead, we're going to use a new-fangled RubyMotion library called BubbleWrap.

BubbleWrap It Up

As we mentioned earlier, BubbleWrap is a collection of idiomatic Ruby wrappers for the iOS SDK. If you haven't noticed, a lot of Apple's APIs use a system of calling established methods on a callback object. Thus, many of BubbleWrap's wrappers are just moving those callback methods into lambdas and blocks. The BubbleWrap::HTTP wrapper we're going to use is an example of that.

Remember to add the requirement in your Rakefile so you're good to go:

require 'motion/project'
require 'bubble-wrap'


The BubbleWrap::HTTP library uses functions for each HTTP request method: HTTP.get,, HTTP.put, etc. Each method takes as arguments a string URL, an options hash, and a callback block for when the request finishes. Here are some short and sweet examples:

BubbleWrap::HTTP.get("") do |response|
  p response.body.to_str

# BW is alias for BubbleWrap
BW::HTTP.get("", payload: {q: "some query"}) do |response|
  # sends request to
end"", payload: {message: "This is a comment"}) do |response|
  # sends request to
  # with body params `message=This is a comment`

Looks pretty nice, right? We can add more information to our requests (like files, headers, HTTP auth credentials), but the APIs we're going to play with just use GET and POSTs. (you can check the full HTTP documentation for details)

Wait a second, what are we actually going to make?

Get ready for an example on how to build an API-driven App!

Like it? Spread the word