Thursday, 29 June 2017

Json Get & Post in Swift (Alamofire)

Json Get & Post in Swift Using Alamofire



1 ) Create New Project AlamofireDemo .

2 ) Open Terminal and go to Path of Project Folder .

3 )  init Pod Using Below Command .

    
   $ pod init

4 ) Open Podfile Then Write & Save File:


pod 'Alamofire', '~> 4.4'


5 ) Install Pod Using Below Command in Terminal :

$ pod install

6 ) Now open AlamofireDemo.xcworkspace :

Write Below Coding For Get and Post :





import UIKit

import Alamofire

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.GetMethod()
        
        self.PostMethod()
        
    }
    
    func GetMethod() {
        
        Alamofire.request("https://httpbin.org/get").responseJSON { response in
            print("Request: \(String(describing: response.request))")   // original url request
            print("Response: \(String(describing: response.response))") // http url response
            print("Result: \(response.result)")                         // response serialization result
            
            if let json = response.result.value {
                print("JSON: \(json)") // serialized json response
            }
            
            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)") // original server data as UTF8 string
            }
        }
        

    }
    
    func PostMethod() {
        
        let parameters: Parameters = [
            "foo": "bar",
            "baz": ["a", 1],
            "qux": [
                "x": 1,
                "y": 2,
                "z": 3
            ]
        ]
        
        Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON{ response in
            print("Request: \(String(describing: response.request))")   // original url request
            print("Response: \(String(describing: response.response))") // http url response
            print("Result: \(response.result)")                         // response serialization result
            
            if let json = response.result.value {
                print("JSON: \(json)") // serialized json response
            }
            
            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)") // original server data as UTF8 string
            }
        }

        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}







No comments:

Post a Comment