Ahmad Naser Turnkey Ecosystem Ahmad Naser
July 25, 2019

Simple Swift Post Request using Task and Alamofire

Published in the Ahmad Naser ecosystem. Estimated reading time: 2 minutes.

Simple Swift Post Request using Task

you need to use the following in your controller
import UIKit
import ObjectMapper
import SwiftyJSON
import Alamofire

    func postToServer(userID : Int) {
        let headers = [
            "\(GlobalConstants.ApiKey)": "\(GlobalConstants.ApiKeyValue)",
            "Accept": "*/*",
            "Cache-Control": "no-cache",
            "Host": "example.com",
            "accept-encoding": "gzip, deflate",
            "Connection": "keep-alive",
            "cache-control": "no-cache"
        ]
     
 let endpoint = "\(GlobalConstants.get_messages)"
 let postString = "user_id=\(userID)";
      let endpointUrl = URL(string: endpoint)
        do {

            var request = URLRequest(url: endpointUrl!)
            request.httpMethod = "POST"
            request.httpBody = postString.data(using: String.Encoding.utf8);
            request.allHTTPHeaderFields = headers
            let task = URLSession.shared.dataTask(with: request){ (data, response, error) in
                if let error = error {
                    print("error: \(error)")
                } else {
                    if let response = response as? HTTPURLResponse {
                        print("statusCode: \(response.statusCode)")
                    }
                    

                  
                    if let data = data, let dataString = String(data: data, encoding: .utf8) {
                        
                        print("data: \(dataString)")
                      //
                          do {
                            
                    
                            let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:Any]
                           
 
                          } catch let parseError as NSError {
                            print("JSON Error \(parseError.localizedDescription)")
                        }
                    }
                }
                    
                
            }
            task.resume()
            
            
        }catch{
        }

    }
    


}

Also you could use Alamofire to return response string

    func getMessages(userID : Int) {

     
 let endpoint = "\(GlobalConstants.get_messages)"

      let endpointUrl = URL(string: endpoint)

   

            
           // view.showHUD(view)
            

          
            
            
            let url = endpointUrl!
        var _id :  NSString = NSString(string: "\(userID)")
            print(url)
            let parameters : [String : NSString] = [
                "user_id":   _id]
            let headers    = [ "\(GlobalConstants.ApiKey)": "\(GlobalConstants.ApiKeyValue)"]
            
            
            Alamofire.request(url, method: .post, parameters: parameters, headers: headers).responseString{ response in
                
         
                
                
             //   debugPrint(response)
                
                switch response.result {
                case .success:
                    print(response.response?.statusCode)
                    print(response.result.value!)
                case .failure:
                   print("\(response.error)")
                }
                
                
         
                
                    
            }
            
            
       
 

    
        
    }

or you could return response as json

    func getMessages(userID : Int) {

     
 let endpoint = "\(GlobalConstants.get_messages)"

      let endpointUrl = URL(string: endpoint)

   

            
           // view.showHUD(view)
            

          
            
            
            let url = endpointUrl!
        var _id :  NSString = NSString(string: "\(userID)")
            print(url)
            let parameters : [String : NSString] = [
                "user_id":   _id]
            let headers    = [ "\(GlobalConstants.ApiKey)": "\(GlobalConstants.ApiKeyValue)"]
            
            
            Alamofire.request(url, method: .post, parameters: parameters, headers: headers).responseJSON() { response in
                
         
                
                
             //   debugPrint(response)
                
                switch response.result {
                case .success:
                    print(response.response?.statusCode)
                    print(response.result.value!)
                    
                    let json = JSON(response.result.value)
                    
                    let dictionaryPost = NSMutableDictionary()
                    
                    if let id = json["uid"].int {
                        dictionaryPost.setValue(id, forKey: "uid")
                        print("here here \(id)")
                    }
                    
                case .failure:
                   print("\(response.error)")
                }
                
                
         
                
                    
            }
            
            
       
 

    
        
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

Leave a Reply

Your email address will not be published. Required fields are marked *