Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to send a request with parameters in Alamofire

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 514
    Comment on it

    Alamofire is HTTP networking library for iOS and Mac OS X, which is written in swift. Alamofire is based on NSURLSession,but it make network code much easy to write.
    Following function is available in Alamofire.

    •  .upload
    •  .download
    •  .request

    Here is a small example on how to work with Alamofire.
    Firstly install pod  to use Alamofire, add below line to your podfile.

    pod 'Alamofire', '~> 3.1.2'

    After installing pod,go to your viewController class and import Alamofire above your class like this

    import Alamofire

    Now do following line of code in your viewController.

    func fetchRequest(){
            Alamofire.request(
                            .GET,
                            Put your url string here,
                            parameters: [key: value],
                            encoding: .URL).validate().responseJSON { (Response) -> Void in
                                guard Response.result.isSuccess else{
                                    print("error is \(Response.result.error)")
                                    return
                                }
                                print("result is \(Response.result.value)")
            }
    
        }
    

    Here we use .validate() to simplifies error condition handling on Response object and responseJSON(completionHandler:) for deserialize the response.
    The reason for using guard is if the condition passes, the optional variable automatically unwrapped within the scope of guard statement was called. Another reason is for checking bad cases early, making function more readable and easier to maintain.

    Now edit your “viewDidLoad()” function.

    override func viewDidLoad() {
            super.viewDidLoad()
             fetchRequest()
            // Do any additional setup after loading the view.
        }

    And run your app.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: