Search code examples
iosswiftxcodeswift2alamofire

Alomofire POST request in swift


I am using the following code in my swift 2.0 project. I cannot add Alamofire.request though I added "import Alamofire". I have to create object of Alamofire and then access through it.

This is how I create the object :

let manager = Alamofire.Manager.sharedInstance
manager.request(NSURLRequest(URL: NSURL(string: "http://httpbin.org/get")!))

let parameters = ["foo": "bar"]

manager.request(.POST, "url", parameters: parameters)
.responseJSON { request, response, json, error in
print("request: \(request)")
}

I am new to both Alamofire and swift. Can anybody tell how can I get response from the above code in a completion handler and why I cannot use Alamofire.request instead of manager.request.


Solution

  • Request not always in JSON please check your request :

    Following are examples to use Alamofire with the Swift 2 :

    GET - JSON

    Alamofire.request(.GET, "http://api.androidhive.info/contacts/", parameters: nil, encoding: .JSON, headers: nil).responseJSON { (req, res, json) -> Void in
        print("\(res?.allHeaderFields)")
        print("\(json.value!)")
    }
    

    POST - without JSON

    Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar"], encoding: .URL, headers: nil).response { (req, res, data, error) -> Void in
        print(res)
        print(data)
    
        let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
        print(dataString)
    }