Search code examples
swiftalamofire

How to install properly Alamofire SwiftyJSon and Alamofire-SwiftyJson


Has you can see from my previous questions, I got a lot of trouble parsing JSON Data. After few days of headache with that, I think the best way still to use alamofire/swiftyjson. I also found the alamofire-swiftyjson to let everything working well together.

But I am not sure how to install this three "libraries" together.

I download the whole Alamofire pack inside my project, I add the SwiftyJson.swift in my project and finally download the Alamofire-SwiftyJson in my project.

But when I change my alamofire request with "responseSwiftyJSON" I get an error saying " "Request" does not have a member name "responseSwiftyJSON

   Alamofire.request(.GET, "http://mysiteweb.com/app/data/jsonpersodata.php", parameters: ["username": username]).responseSwiftyJSON { (request, response, data, error) 

Solution

  • Add Alamofire and SwiftyJSON to the project. Then you can use Alamofire to request the data from the server and SwiftyJSON for serialization.

    Alamofire 4

    Alamofire.request(url).responseJSON { response in
        guard let data = response.data else {
            // No data returned
            return
        }
    
        let json = JSON(data: data)
        print(json)
    }
    

    Alamofire 3

    Alamofire.request(.GET, url).validate().responseJSON { response in
        switch response.result {
        case .Success:
            if let jsonData = response.result.value {
              let json = JSON(jsonData)
              print(json)
            }
        case .Failure(let error):
            print(error)
        }
    }
    

    Alamofire 2

    Alamofire.request(.GET, "http://api.example.com", parameters: ["username" : username])
            .responseJSON { request, response, data, error in
    
            let swiftyJSONObject = JSON(data: data!)
    }
    

    Note that you have to unwrap data because server may return nothing.