Swift: How to use library: Alamofire-SwiftyJSON

DannieCoderBoi picture DannieCoderBoi · Feb 3, 2015 · Viewed 9.1k times · Source

I'm having trouble trying to get this library Alamofire-SwiftyJSON (https://github.com/SwiftyJSON/Alamofire-SwiftyJSON) to work.

I created a new project and downloaded the Alamofire-SwiftyJSON library and dragged everything into my project navigation area.

However when I go into the ViewController and add:

import AlamofireSwiftyJSON

I get the error: no such module import AlamofireSwiftyJSON

Can someone tell me how to add this project manually. Ideally step by step so that I can get this code to work:

 Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
     .responseSwiftyJSON { (request, response, json, error) in
                 println(json)
                 println(error)
               }

Thank you

Answer

MarkP picture MarkP · Feb 3, 2015

What is your Deployment Target? is it < 8.0 ? if so those targets that do not support embedded frameworks and as such all you need to do is:

  • Drag Alamo.Swift to your project Navigation (Make sure you copy files if needed)
  • Remove instances of 'Usage' Alamofire.request will become request

so the code you have will be:

request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
 .responseSwiftyJSON { (request, response, json, error) in
             println(json)
             println(error)
           }

So now, that is that framework. Since I have some time now I will show you how to get it all working and neaten it up a little.

Once you have done the above, do this:

  • drag SwiftyJSON.swift to your project navigation area

Again... Make sure you copy files if needed. That is it for the framework also.

Right to neaten it up a little - You don't have to do this but its always better to use variables and arrays where possible to make cleaner and speed up coding time. For your example above do this:

var url = "http://httpbin.org/get"
var arr_parameters = [
    "foo": "bar"
]

request(.GET, url, parameters: arr_parameters)

Its also a good idea to incorporate some error testing so that you can debug things easier and also provide fallbacks etc...

so, with this in mind, your entire code should look like:

var url = "http://httpbin.org/get"
var arr_parameters = [
    "foo": "bar"
]

request(.GET, url, parameters: arr_parameters)
   .responseJSON { (req, res, json, error) in
            if(error != nil) {
                NSLog("Error: \(error)")
                println(req)
                println(res)
            }
            else {
                NSLog("Success: \(url)")
                var json = JSON(json!)
            }
    }

There was a really good article covering this in SwiftMonthly

I hope this helps. Good luck and keep us posted.