iosswiftswift2

How to send data to the server (API) using swift


I am developing a app using swift2 am having API key in JSON format I can able to work with that and it provides some data such as success:1,error:0. If I get the value success 1 means I want to send the entered data or saved data to a server (API key). How to do that?


Solution

  • you can send data to server by using Alamofire API. It's documention and implemention all the stuff are mentioned in the following link.

    https://github.com/Alamofire/Alamofire

    Just install it using Pods and it's very easy to implement.

    create Network Class and create following function inside it.

       func get_Request(currentView : UIViewController,action : NSString,completionHandler: (NSDictionary -> Void)) {
        print("Url==>>>",mainURl + (action as String))
    
        Alamofire.request(.GET,mainURl + (action as String), parameters: nil)
            .responseJSON { response in
    
                if let JSON = response.result.value {
                    completionHandler(JSON as! NSDictionary)
                }
                else{
                    printf(response.result.error?.localizedDescription)
                }
            }
    }
    

    Other class

    viewDidLoad{
        NetworkClass.get_Request(self,action: "yourServiceName/" + (yourParameters as String), completionHandler: self.resultHandler)
    }
    func resultHandler(result : NSDictionary) -> Void {
    
        printf("result is -->>",result)
    
    }